Problem
This is because in your function you are dealing with a local variable x on the left side and a global variable x on the right side. You do not update global x in the function, but you assign the value 101 local x . Each time you call the function, the same thing happens, so you assign local x 101 5 times and print it 5 times.
To visualize:
# this is the "global" scope x <- 100 f <- function(){
This will look like the following code:
y <- 100 f <- function(){ x <- y + 1 print(x) }
One possible fix
How to do it to fix it. Take the variable as an argument and pass it as an update. Something like that:
f <- function(old.x) { new.x <- old.x + 1 print(new.x) return(new.x) }
You need to keep the return value, so your updated code will look like this:
x <- 100 f <- function(old.x) { new.x <- old.x + 1 print(new.x) return(new.x) } for (i in 1:5) { x <- f(x) }
joneshf
source share