Parse and Evaluate Expressions from a File

Parses expressions in the given file, and then successively evaluates them in the specified environment.

utilities, file
sys.source(file, envir = baseenv(), chdir = FALSE,
           keep.source = getOption("keep.source.pkgs"),
  = getOption(""),
           toplevel.env = as.environment(envir))

a character string naming the file to be read from


an R object specifying the environment in which the expressions are to be evaluated. May also be a list or an integer. The default value NULL corresponds to evaluation in the base environment. This is probably not what you want; you should typically supply an explicit envir argument.


logical; if TRUE, the R working directory is changed to the directory containing file for evaluating.


logical. If TRUE, functions keep their source including comments, see options(keep.source = *) for more details.

logical. If TRUE and keep.source is also TRUE, functions keep parse data with their source, see options( = *) for more details.


an R environment to be used as top level while evaluating the expressions. This argument is useful for frameworks running package tests; the default should be used in other cases


For large files, keep.source = FALSE may save quite a bit of memory. Disabling only parse data via = FALSE can already save a lot. In order for the code being evaluated to use the correct environment (for example, in global assignments), source code in packages should call topenv(), which will return the namespace, if any, the environment set up by sys.source, or the global environment if a saved image is being used.

See Also

source, and library which uses sys.source.

  • sys.source
library(base) # NOT RUN { ## a simple way to put some objects in an environment ## high on the search path tmp <- tempfile() writeLines("aaa <- pi", tmp) env <- attach(NULL, name = "myenv") sys.source(tmp, env) unlink(tmp) search() aaa detach("myenv") # }

Community examples

Looks like there are no examples yet.