Examples for 'R.utils::sourceTo.default'


Parses and evaluates code from a file or a connection

Aliases: sourceTo.default sourceTo

Keywords: programming IO

### ** Examples

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example 1
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cat("=== Example 1 ================================================\n")
=== Example 1 ================================================
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")
Global objects before calling foo():
lsBefore <- NA
lsBefore <- ls()
foo(file=textConnection(c('a <- 1', 'b <- 2')))
Local objects before calling sourceTo():
[1] "file"
Local objects after calling sourceTo():
[1] "a"    "b"    "file" "res" 
cat("Global objects after calling foo():\n")
Global objects after calling foo():
stopifnot(length(setdiff(ls(), lsBefore)) == 0)


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Example 2 - with VComments preprocessor
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cat("=== Example 2 ================================================\n")
=== Example 2 ================================================
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)
-----------------------------------------
Source code before preprocessing:
Warning: error in running command
-----------------------------------------
Source code after preprocessing:
Warning: error in running command
-----------------------------------------
[1] "Hello world"
setHook("sourceTo/onPreprocess", oldHooks, action="replace")

[Package R.utils version 2.11.0 Index]