Is it possible to move variables that reside in the global environment into a separate environment to declutter the global namespace? I understand how to create variables in a separate environment (with(env, ...)) but is there an efficient way to move them after creation in the global environment. I suppose it would be possible to copy them into a separate environment and then remove them from the global environment, but wanted to know if there was a more efficient manner.
Is it possible to move a variable from the global environment into a separate environment?
616 Views Asked by kamiks At
4
There are 4 best solutions below
0
On
Not sure if this is a good idea but you can attach them to the search path. Starting with a fresh vanilla R session try this.
a <- 1
b <- 2
attach(as.list(.GlobalEnv), name = "myenv")
rm(a, b)
ls("myenv")
ls()
a
b
3
On
You may use multiple lines in the with.
e1 <- new.env()
e2 <- new.env()
with(e1, {
k <- l <- m <- 0L
x <- 1
fo <- y ~ x
fun <- function(x) x^2
})
The objects are created in e1,
ls(e1)
# [1] "fo" "fun" "k" "l" "m" "x"
e2 stays empty,
ls(e2)
# character(0)
and in .GlobalEnv only the environments exist so far.
ls(.GlobalEnv)
# [1] "e1" "e2"
To work with objects, also use with or $.
with(e1, fun(2))
# [1] 4
e1$fun(2)
# [1] 4
Maybe:
Or
Created on 2021-12-31 by the reprex package (v2.0.1)