[Rd] The enclosed environment does not work as expected
Jiefei Wang
@zwj|08 @end|ng |rom gm@||@com
Sun Apr 3 05:32:13 CEST 2022
Hi,
It seems like the enclosed environment does not work well with the
loop. Here is a simple example
```
FuncGenerator <- function(value){
function() message(value)
}
funcSets <- list()
for(i in 1:2)
funcSets[[i]] <- FuncGenerator(i)
environment(funcSets[[1]])$value
# [1] 2
environment(funcSets[[2]])$value
# [1] 2
```
The output from the last two lines is simply 2. I expect the first
should be 1 and the second is 2. However, if I ask R to execute the
message function before accessing its environment, the result is
correct again.
```
FuncGenerator <- function(value){
function() message(value)
}
funcSets <- list()
for(i in 1:2)
funcSets[[i]] <- FuncGenerator(i)
## Ask to evaluate the function
for(i in 1:2){
funcSets[[i]]()
}
# 1
# 2
environment(funcSets[[1]])$value
# [1] 1
environment(funcSets[[2]])$value
# [1] 2
```
This does not make any sense to me since the function simply prints
out its variable `value`. It should not change the value of the
variable, so I think this might be a bug in the code optimizer. This
issue can only be corrected by the loop(like the second example),
manually evaluating the function without the loop will give you the
same result as the first example.
Here is my session information
> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)
Best,
Jiefei
More information about the R-devel
mailing list