for loop on R function -
i'm new r (and programming generally), , confused why following bits of code yield different results:
x <- 100 for(i in 1:5){ x <- x + 1 print(x) }
this incrementally prints sequence 101:105 expect.
x <- 100 f <- function(){ x <- x + 1 print(x) } for(i in 1:5){ f() }
but prints 101 5 times.
why packaging logic function cause revert original value on each iteration rather incrementing? , can make work repeatedly-called function?
the problem
it because in function dealing local variable x
on left side, , global variable x
on right side. not updating global x
in function, assigning value of 101
local x
. each time call function, same thing happens, assign local x
101
5 times, , print out 5 times.
to visualize:
# "global" scope x <- 100 f <- function(){ # "global" x has value 100, # add 1 it, , store in new variable x. x <- x + 1 # new x has value of 101 print(x) }
this similar following code:
y <- 100 f <- function(){ x <- y + 1 print(x) }
one possible fix
as fix it. take variable argument, , pass update. this:
f <- function(old.x) { new.x <- old.x + 1 print(new.x) return(new.x) }
you want store return value, updated code like:
x <- 100 f <- function(old.x) { new.x <- old.x + 1 print(new.x) return(new.x) } (i in 1:5) { x <- f(x) }
Comments
Post a Comment