View source: R/attach_source.R
attach_source | R Documentation |
Source R files in an attached environment
attach_source( ..., name = as_tidy_env_name(c(...), prefix = "source:"), recursive = FALSE, pos = 2L, chdir = FALSE, warn.conflicts = TRUE, mask.ok = NULL )
... |
filepaths to R files, or paths to directories containing R files. |
name |
A string, the name for the attached environment. By default, the
name is constructed from paths supplied to |
recursive |
If directories are passed to |
pos |
The position where to attach the environment, if creating a new
one. If an environment of |
chdir |
logical. if TRUE, the R working directory is temporarily changed to the directory containing the file(s) being sourced. |
warn.conflicts |
logical. If TRUE (the default), print warnings about objects in the attached environment that that are masking or masked by other objects of the same name. |
mask.ok |
character vector of names of objects that can mask objects on
the search path without signaling a warning if |
The attached environment, invisibly.
One subtlety that is sometimes important: packages attached after this
environment is created will be not on the symbol search path for the environment
where the R source is evaluated. The search path of the environment the R
files are sourced in is tail(search(), -pos)
.
This means that, for example, if you source a script that calls
library()
, the code in that script will not "see" the functions from the
newly attached packages. This is by design. However, if you want to source
scripts that call library
and define new functions, and you want those
new functions to "see" the library
attached packages, here are 3 ways to
do that:
Attach all the packages you want before attaching the script:
library(foo); library(bar) attach_source("my_script.R")
Modify the default pos
argument to library
, so all new packages
attach after your script:
envir:::set_default_library_pos(after = "source:my_script.R") attach_source("my_script.R")
This is the likely the most preferred solution. Instead of sourcing
files directly in the attached environment, source the files into a new
environment that inherits from .Globalenv
, and then copy over everything
to the attached environment.
attach_eval({ import_from("my_script.R") })
import_from, set_library_default_pos
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.