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
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 }
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)}
source share