This happens because assign
modifies the parent environment. In the case of for, the parent environment is the global environment itself. So the variables appear to you.
In the case of a function being called by map
or lapply
, the parent environment is the environment of the calling function itself, and that environment is destroyed shortly after the function is executed.
You can see the environment that the function is using with the environment
function:
> 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>
One way to modify lapply
or map
to work the way you imagine it is to specify the environment for the assign
function:
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
you are probably making a code that would look better if you used a named list.
Worth reading the chapter on Advanced R environments: link