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