Just use the local=TRUE argument for source and evaluate source somewhere other than your global environment. Here are some ways to do this (assuming you don't want to have access to variables in the script). foo.R contains only print(x <- 1:10) .
do.call(source, list(file="c:/foo.R", local=TRUE), envir=new.env()) # [1] 1 2 3 4 5 6 7 8 9 10 ls() # character(0) mysource <- function() source("c:/foo.R", local=TRUE) mysource() # [1] 1 2 3 4 5 6 7 8 9 10 ls() # [1] "mysource"
sys.source is probably the most direct solution.
sys.source("c:/foo.R", envir=new.env())
You can also evaluate the file in a connected environment if you want to access variables. See the examples in ?sys.source for how to do this.
Joshua ulrich
source share