This happens because the assign
modifies the parent environment. In the case of the parent environment, the parent environment is the global environment itself. That’s why variables appear to you.
In the case of a function being called by map
or of lapply
, the parent environment is the environment of the function itself that is calling, and that environment is destroyed soon after the execution of the function.
You can see the environment the function is using with the function environment
:
> for(i in 1:6){
+ names<-str_c('var',i)
+ print(environment())
+ assign(names,runif(30,20,100))
+ }
<environment: R_GlobalEnv>
<environment: R_GlobalEnv>
<environment: R_GlobalEnv>
<environment: R_GlobalEnv>
<environment: R_GlobalEnv>
<environment: R_GlobalEnv>
> lapply(1:6,function(i){
+ names<-str_c('var',i)
+ print(environment())
+ assign(names,runif(30,20,100))
+ })
<environment: 0x14eec3a0>
<environment: 0x2bd9e368>
<environment: 0x13b43ae0>
<environment: 0xe7213c0>
<environment: 0x13dc00d8>
<environment: 0x1a7aab10>
A way to modify the lapply
or the map
to work the way you imagine is to specify Environment for the function assign
:
lapply(1:6,function(i){
names<-str_c('var_lapply_',i)
assign(names,runif(30,20,100), envir = .GlobalEnv)
})
Note: If you need to use assign
is probably making a code that would look better if it used a named list.
Read the Advanced R Nvironments chapter: https://adv-r.hadley.nz/environments.html
What the code would look like with
lapply
andmap
, then?– neves