Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R set all variables to Global Environment [closed]

Tags:

r

Is there a way to set all variables within a local environment to global Environment? I know how to do this for single variable. What if I have 30+ variables? Can I send all local workspace into global? Thanks.

myfunction=function(){
    assign("a", 10, envir = .GlobalEnv)
}
myfunction()
print (a)

or in case of Rnw file. I can do

a=3
environment(a)=.GlobalEnv
like image 363
DrunkenMunky Avatar asked Oct 13 '25 01:10

DrunkenMunky


1 Answers

As a function, allglobal(), gets the objects (vars and functions) in the environment it was called (parent.frame) and assigns all of them to the global environment. The second function is a test. After it is run, "test1" and "test2" exist in the global environment:

allglobal <- function() {
    lss <- ls(envir = parent.frame())
    for (i in lss) {
        assign(i, get(i, envir = parent.frame()), envir = .GlobalEnv)
    }
}

testallglob <- function() {
    test1 <- 1
    test2 <- function() 2
    allglobal()
}
like image 68
S.C Avatar answered Oct 14 '25 17:10

S.C