0

In the following snipped I am assigning functions to spots in a list. The result changes depending on whether I am using a paste in the loop. I would, up to now, have guessed that calling print would not change any objects, so I am very confused. In particular, I would be interested how I should create functions in a loop, such that they stay different.

g <- function(x){
    function(y){
        10*x + y
    }
}

#############  

test <- list()

x=1

test[[x]] <- g(x)
test[[x]](1) # 11

x=2
test[[x]] <- g(x)
test[[x]](1) # 21
test[[1]](1) # still 11
####

test2 <- list()

for(z in 1:2){
    test2[[z]] <- g(z)
}

test2[[1]](1) # 21 Without print

###

test3 <- list()

for(z in 1:2){
    test3[[z]] <- g(z)
    print(paste("z=",z,"Result=",test3[[z]](1)))
}

test3[[1]](1) # 11 with print
  • 2
    It's not a scoping issue. It's lazy evaluation. By default, R expressions are only evaluated when they're "needed". Printing an object inside the loop means its value is needed inside the loop. Without the `print`, it's not needed until outside the loop, when the loop index has a single, out-of-bounds value. This is a very common cause of errors and is why I prefer `lapply` to `for`, since `lapply` forces evaluation. – Limey Aug 18 '22 at 11:52
  • 1
    See, for example, [this](http://adv-r.had.co.nz/Functions.html#function-arguments). – Limey Aug 18 '22 at 11:56

0 Answers0