Examples for 'base::source'


Read R Code from a File, a Connection or Expressions

Aliases: source withAutoprint

Keywords: file programming connection

### ** Examples

someCond <- 7 > 6
## want an if-clause to behave "as top level" wrt auto-printing :
## (all should look "as if on top level", e.g. non-assignments should print:)
if(someCond) withAutoprint({
   x <- 1:12
   x-1
   (y <- (x-5)^2)
   z <- y
   z - 10
})
> x <- 1:12
> x - 1
 [1]  0  1  2  3  4  5  6  7  8  9 10 11
> (y <- (x - 5)^2)
 [1] 16  9  4  1  0  1  4  9 16 25 36 49
> z <- y
> z - 10
 [1]   6  -1  -6  -9 -10  -9  -6  -1   6  15  26  39
## If you want to source() a bunch of files, something like
## the following may be useful:
 sourceDir <- function(path, trace = TRUE, ...) {
    op <- options(); on.exit(options(op)) # to reset after each 
    for (nm in list.files(path, pattern = "[.][RrSsQq]$")) {
       if(trace) cat(nm,":")
       source(file.path(path, nm), ...)
       if(trace) cat("\n")
       options(op)
    }
 }

suppressWarnings( rm(x,y) ) # remove 'x' or 'y' from global env
withAutoprint({ x <- 1:2; cat("x=",x,"\n"); y <- x^2 })
> x <- 1:2
> cat("x=", x, "\n")
x= 1 2 
> y <- x^2
## x and y now exist:
stopifnot(identical(x, 1:2), identical(y, x^2))

withAutoprint({ formals(sourceDir); body(sourceDir) },
              max.deparse.length = 20, verbose = TRUE)
'envir' chosen:<environment: 0x55ccff53f170>

>>>> eval(expression_nr. 1 )
		 =================
> formals(sourceDir)
curr.fun: symbol formals
$path


$trace
[1] TRUE

$...


 .. after 'expression(formals(sourceDir))'

>>>> eval(expression_nr. 2 )
		 =================
> body(sourceDir)
curr.fun: symbol body
{
    op <- options()
    on.exit(options(op))
    for (nm in list.files(path, pattern = "[.][RrSsQq]$")) {
        if (trace) 
            cat(nm, ":")
        source(file.path(path, nm), ...)
        if (trace) 
            cat("\n")
        options(op)
    }
}
 .. after 'expression(body(sourceDir))'

[Package base version 4.2.3 Index]