For a cycle in function R

I am new to R (and generally programming) and confused why the following bits of code give different results:

x <- 100 for(i in 1:5){ x <- x + 1 print(x) } 

This steps out 101: 105, as you would expect.

 x <- 100 f <- function(){ x <- x + 1 print(x) } for(i in 1:5){ f() } 

But it just prints 101 five times.

Why does packing logic into a function make it return the original value at each iteration, rather than increase it? And what can I do to make this work a multi-called function?

+7
source share
2 answers

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(){ # Get the "global" x which has value 100, # add 1 to it, and store it in a new variable x. x <- x + 1 # The new x has a value of 101 print(x) } 

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) } 
+15
source

This does what you want:

 f <- function(){ x <<- x + 1 print(x) } 

But you should not do that . Globals are not a good construction. Functions with side effects make the code hard to understand and hard to debug.

A safer way to use the global is to encapsulate it in another environment. Here is an example:

 create.f <- function(x) { return(function() { x <<- x + 1 print(x) }) } f <- create.f(100) for (i in 1:5) f() ## [1] 101 ## [1] 102 ## [1] 103 ## [1] 104 ## [1] 105 

Here global x is in the environment of the body create.f , where f is defined, not the global environment. A function environment is the environment in which it is defined (and not the one in which it is called).

+2
source

All Articles