How to fix R code without overwriting current variables?

I am trying to get the results by executing the R code using the source command. Since there are variables with the same name, the variables in the R executable will overwrite the current variables. How to get 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 only want to get a from sub.R without b in main.R , which will be overwritten with the same name variable in sub.R Essentially, I want to execute the R file as a method call with saving the return value.

+5
source share
1 answer

You can specify content in a specific environment with sys.source if you want. for instance

 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 are looking for source files, such as functions, you should just include the function in the source file and then call that function in your main file. Do not try to circumvent values ​​in the environment at all. for instance

 # 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 the source 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 
+7
source

Source: https://habr.com/ru/post/1213822/


All Articles