rr-environment

Is it possible to move a variable from the global environment into a separate environment?


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.


Solution

  • Maybe:

    library(purrr)
    
    a <- 111
    b <- 'hello'
    
    my_envir <- new.env()
    
    names(.GlobalEnv) %>% 
        walk(~ assign(.x, get(.x), envir = my_envir))
    
    eapply(my_envir, function(x) x)
    #> $my_envir
    #> <environment: 0x7fed59e56dc8>
    #> 
    #> $a
    #> [1] 111
    #> 
    #> $b
    #> [1] "hello"
    

    Or

    library(purrr)
    a <- 111
    b <- 'hello'
    my_envir <- new.env()
    
    eapply(.GlobalEnv, function(x) x) %>% 
        discard(is.environment) %>% 
        {walk2(., names(.), ~{
                   assign(.y, .x, envir = my_envir)
                   exec('rm', .y, envir = .GlobalEnv)}
    )}
    
    
    eapply(my_envir, function(x) x)
    #> $a
    #> [1] 111
    #> 
    #> $b
    #> [1] "hello"
    

    Created on 2021-12-31 by the reprex package (v2.0.1)