I would like to evaluate some code in the environment which will have
the access to libraries (all environments above .GlobalEnv) but won't have
access to the objects created in the .GlobalEnv.
I've tried couple solutions but none seemed to work as expected
1. new environment in .GlobalEnv
Here environment created in the .GlobalEnv have an access to the other
objects in the .GlobalEnv.
.GlobalEnv$ee <- environment()
eval(
parse(text = "library(dplyr);mutate(iris, x = 1)"),
envir = .GlobalEnv$ee
)
var_in_global <- "x"
eval(
expr = parse(text = "ls()"),
envir = .GlobalEnv$ee
) # expect empty
eval(
expr = parse(text = "print(var_in_global)"),
envir = ee
) # expect error
2. New environment as a child of .GlobalEnv
This one is Coded different way but result is th same as 1st
ee <- new.env(parent = globalenv())
eval(
parse(text = "library(dplyr);mutate(iris, x = 1)"),
envir = ee
)
var_in_global <- "x"
eval(
expr = parse(text = "ls()"),
envir = ee
)
eval(
expr = parse(text = "print(var_in_global)"),
envir = ee
)
3. New environment as parent of global
In this case environment doesn't have an access to the .GlobalEnv objects
but libraries loaded after will be attached below, so the environment doesn't
have an access to these libraries as well.
ee <- new.env(parent = parent.env(globalenv()))
eval(
parse(text = "library(dplyr);mutate(iris, x = 1)"),
envir = ee
)
var_in_global <- "x"
eval(
expr = parse(text = "ls()"),
envir = ee
)
eval(
expr = parse(text = "print(var_in_global)"),
envir = ee
)
4. Using library(..., pos = 3)
Using answer from @Allan Cameron, I've tried to make this code working. And library(dplyr);mutate(...) were correctly evaluated in new environment.
ee <- new.env(parent = parent.env(globalenv()))
eval(
parse(text = "library <- function(...) base::library(..., pos = 3)"),
envir = ee
)
eval(
parse(text = "library(dplyr);mutate(iris, x = 1)"),
envir = ee
)
var_in_global <- "x"
eval(
expr = parse(text = "ls()"),
envir = ee
)
eval(
expr = parse(text = "print(var_in_global)"),
envir = ee
)
However, problem is much deeper. Some packages have more dependencies which are loaded along. Consider this example where I've replaced library(dplyr);mutate() with library(Hmisc);impute(...). This example fails - couldn't find impute function (which is wrong)
ee <- new.env(parent = parent.env(globalenv()))
eval(
parse(text = "library <- function(...) base::library(..., pos = 3)"),
envir = ee
)
eval(
parse(text = "library(Hmisc);impute(iris[,1], 1)"),
envir = ee
) # expect to work
Do you have any ideas how to make an environment which will be "parallel" node to the global, and still have libraries attached before?