sourceTo | R Documentation |
Parses and evaluates code from a file or a connection.
This has the same effect as if source(..., local=TRUE)
would have
been called from within the given environment.
This is useful when setting up a new local working environment.
## Default S3 method:
sourceTo(file, path=NULL, chdir=FALSE, ..., local=TRUE, envir=parent.frame(),
modifiedOnly=FALSE)
file |
A |
path |
An optional |
chdir |
If |
... |
Arguments to |
local |
If |
envir |
An |
modifiedOnly |
If |
Return the result of source
().
This methods recognizes the hook sourceTo/onPreprocess
, which
is called after the lines in file has been read, but before they have
been parsed by the R parser, cf. parse
().
An onPreprocess
hook function should take a character
vector
of code lines and return a character
vector
of code lines.
This can for instance be used to pre-process R source code with special
directives such as VComments
.
Note that only one hook function can be used for this function, otherwise an error is generated.
Henrik Bengtsson
sourceDirectory
().
sys.source
() and source
().
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example 1
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cat("=== Example 1 ================================================\n")
foo <- function(file, ...) {
cat("Local objects before calling sourceTo():\n")
print(ls())
res <- sourceTo(file, ...)
cat("Local objects after calling sourceTo():\n")
print(ls())
}
cat("Global objects before calling foo():\n")
lsBefore <- NA
lsBefore <- ls()
foo(file=textConnection(c('a <- 1', 'b <- 2')))
cat("Global objects after calling foo():\n")
stopifnot(length(setdiff(ls(), lsBefore)) == 0)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example 2 - with VComments preprocessor
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cat("=== Example 2 ================================================\n")
preprocessor <- function(lines, ...) {
cat("-----------------------------------------\n")
cat("Source code before preprocessing:\n")
displayCode(code=lines, pager="console")
cat("-----------------------------------------\n")
cat("Source code after preprocessing:\n")
lines <- VComments$compile(lines)
displayCode(code=lines, pager="console")
cat("-----------------------------------------\n")
lines
}
oldHooks <- getHook("sourceTo/onPreprocess")
setHook("sourceTo/onPreprocess", preprocessor, action="replace")
code <- c(
'x <- 2',
'#V1# threshold=-1',
'#Vc# A v-comment log message',
'print("Hello world")'
)
fh <- textConnection(code)
sourceTo(fh)
setHook("sourceTo/onPreprocess", oldHooks, action="replace")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.