Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to source R code without overwriting current variables?

Tags:

r

I am trying to retrieve results by executing R code with the source command. Because there are some variables with the same name, the variables in the executed R file will overwrite the current variables. How do I retrieve the result without overwriting the current variables?

#main.R Code
b=0
source('sub.R')
if(a>1){print(T)}else{print(F)}

#sub.R
b=1
test<-function(x){x=1}
a=test(b)

I want to only retrieve a from sub.R without b in main.R being overwritten by the same name variable in sub.R. Essentially, I want to execute a R file like calling a method with just keeping the return value.

like image 507
YYY Avatar asked Feb 20 '15 17:02

YYY


1 Answers

You can source the contents into a specific environment with sys.source if you like. For example

b <- 0
ee <- new.env()
sys.source('sub.R', ee)
ee$a
# [1] 1     # the ee envir has the result of the sourcing
if(ee$a>1) {print(T)} else{print(F)}
# [1] FALSE
b
# [1] 0     #still zero

But if you're looking to source files like they are functions, you should just include a function in the sourced file and then call that function in your main file. Don't try to pass around values in the environment at all. For example

# sub.R  --------------
runsub<-function() {
    b=1
    test<-function(x){x=1}
    a=test(b)
    a
}

# main.R  -------------
b <- 0
source('sub.R')
a <- runsub()
if(a>1){print(T)}else{print(F)}

Or if you want to write a helper function to return a specific value from a sourced environment, you can do

sourceandgetvar <- function(filename, varname) {
    ee <- new.env()
    sys.source(filename, ee)
    stopifnot(varname %in% ls(envir=ee))
    ee[[varname]]
}

Then you can change main.R to

b <- 0
a <- sourceandgetvar("sub.R", "a")
if(a>1) {print(T)} else {print(F)}
# [1] FALSE
b
# [1] 0
like image 71
MrFlick Avatar answered Sep 22 '22 14:09

MrFlick