[R] source files in temp environment

Duncan Murdoch murdoch.duncan at gmail.com
Sat Dec 2 12:01:41 CET 2017


On 02/12/2017 5:48 AM, Alexander Shenkin wrote:
> Hi all,
> 
> I often keep code in separate files for organizational purposes, and
> source() that code from higher level scripts.  One problem is that those
> sourced files often create temporary variables that I don't want to keep
> around.  I could clean up after myself with lots of rm()'s, but that's a
> pain, and is messy.
> 
> I'm wondering if one solution might be to source the code in a temporary
> environment, assign outputs of interest to the .GlobalEnv with <<-, and
> then delete the environment afterwards.  One way to do this:
> 
> file.r:
> temp1 = 1
> temp2 = 2
> desired_var <<- temp1 + temp2
> 
> console:
> temp_e = new.env()
> source("file.r", local = temp_e)
> rm(temp_e)
> 
> It's a bit messy to create and delete environments, so I tried what
> others have referred to:
> 
> source("file.r", local = attach(NULL))
> 
> This, however, results in a persistent "NULL" environment in the search
> path.
> 
>   > search()
> ".GlobalEnv"            "package:bindrcpp"      "NULL"
> "tools:rstudio"         "package:stats"         "package:graphics"
> "package:grDevices"     "package:utils"         "package:datasets"
> "package:methods"       "Autoloads"             "package:base"
> 
> Of course, functions are built to encapsulate like this (and do so in
> their own temporary environment), but in many cases, turning the sourced
> code into functions is possible but clunky.
> 
> Any thoughts or suggestions would be much appreciated.

I would wrap the calls in the local() function, or put them in a 
function and call that.  That is,

local({
   source("file.R", local = TRUE)
})

or

sourceit <- function() {
   source("file.R", local = TRUE)
}
sourceit()

With respect to your last comment (turning the code in file.R into 
functions which don't leave their locals behind):  I think that would be 
the best solution.  You may find it clunky now, but in the long run it 
likely will help you to make better code.

Duncan Murdoch



More information about the R-help mailing list