Movatterモバイル変換


[0]ホーム

URL:


rdrr.io

source: Read R Code from a File, a Connection or Expressions

sourceR Documentation

Read R Code from a File, a Connection or Expressions

Description

source causesR to accept its input from the named file or URLor connection or expressions directly. Input is read andparsed from that fileuntil the end of the file is reached, then the parsed expressions areevaluated sequentially in the chosen environment.

withAutoprint(exprs) is a wrapper forsource(exprs = exprs, ..) with different defaults. Its main purpose is to evaluateand auto-print expressions as if in a toplevel context, e.g, as in theR console.

Usage

source(file, local = FALSE, echo = verbose, print.eval = echo,       exprs, spaced = use_file,       verbose = getOption("verbose"),       prompt.echo = getOption("prompt"),       max.deparse.length = 150, width.cutoff = 60L,       deparseCtrl = "showAttributes",       chdir = FALSE,       encoding = getOption("encoding"),       continue.echo = getOption("continue"),       skip.echo = 0, keep.source = getOption("keep.source"))withAutoprint(exprs, evaluated = FALSE, local = parent.frame(),              print. = TRUE, echo = TRUE, max.deparse.length = Inf,              width.cutoff = max(20, getOption("width")),              deparseCtrl = c("keepInteger", "showAttributes", "keepNA"),              ...)

Arguments

file

a connection or a character string giving thepathname of the file or URL to read from."" indicates theconnectionstdin().

local

TRUE,FALSE or an environment, determiningwhere the parsed expressions are evaluated.FALSE (thedefault) corresponds to the user's workspace (the globalenvironment) andTRUE to the environment from whichsource is called.

echo

logical; ifTRUE, each expression is printedafter parsing, before evaluation.

print.eval, print.

logical; ifTRUE, the result ofeval(i) is printed for each expressioni; defaultsto the value ofecho.

exprs

forsource() andwithAutoprint(*, evaluated=TRUE):instead of specifyingfile, anexpression,call, orlistofcall's, butnot an unevaluated “expression”.

forwithAutoprint() (with defaultevaluated=FALSE):one or more unevaluated “expressions”.

evaluated

logical indicating thatexprs is passed tosource(exprs= *) and hence must be evaluated, i.e., a formalexpression,call orlist of calls.

spaced

logical indicating if newline (hence empty line) shouldbe printed before each expression (whenecho = TRUE).

verbose

ifTRUE, more diagnostics (than justecho = TRUE) are printed during parsing and evaluation ofinput, including extra info foreach expression.

prompt.echo

character; gives the prompt to be used ifecho = TRUE.

max.deparse.length

integer; is used only ifecho isTRUE and gives the maximal number of characters output forthe deparse of a single expression.

width.cutoff

integer, passed todeparse() whichis used (only) when there are no source references.

deparseCtrl

character vector, passed ascontrol todeparse(), see also.deparseOpts. InR version <= 3.3.x, this washardcoded to"showAttributes", which is the defaultcurrently;deparseCtrl = "all" may be preferable, when strictback compatibility is not of importance.

chdir

logical; ifTRUE andfile is a pathname,theR working directory is temporarily changed to the directorycontainingfile for evaluating.

encoding

character vector. The encoding(s) to be assumed whenfile is a character string: seefile. Apossible value is"unknown" when the encoding is guessed: seethe ‘Encodings’ section.

continue.echo

character; gives the prompt to use oncontinuation lines ifecho = TRUE.

skip.echo

integer; how many comment lines at the start of thefile to skip ifecho = TRUE.

keep.source

logical: should the source formatting be retainedwhen echoing expressions, if possible?

...

(forwithAutoprint():) further (non-file related)arguments to be passed tosource(.).

Details

Note that running code viasource differs in a few respectsfrom entering it at theR command line. Since expressions are notexecuted at the top level, auto-printing is not done. So you willneed to include explicitprint calls for things you want to beprinted (and remember that this includes plotting bylattice,FAQ Q7.22). Since the complete file is parsed before any of it isrun, syntax errors result in none of the code being run. If an erroroccurs in running a syntactically correct script, anything assignedinto the workspace by code that has been run will be kept (just asfrom the command line), but diagnostic information such astraceback() will contain additional calls towithVisible.

All versions ofR accept input from a connection with end of linemarked by LF (as used on Unix), CRLF (as used on DOS/Windows) or CR(as used on classic Mac OS) and map this to newline. The final linecan be incomplete, that is missing the final end-of-line marker.

Ifkeep.source is true (the default in interactive use), thesource of functions is kept so they can be listed exactly as input.

Unlike input from a console, lines in the file or on a connection cancontain an unlimited number of characters.

Whenskip.echo > 0, that many comment lines at the start ofthe file will not be echoed. This does not affect the execution ofthe code at all. If there are executable lines within the firstskip.echo lines, echoing will start with the first of them.

Ifecho is true and a deparsed expression exceedsmax.deparse.length, that many characters are output followed by .... [TRUNCATED].

Encodings

By default the input is read and parsed in the current encoding oftheR session. This is usually what is required, but occasionallyre-encoding is needed, e.g. if a file from a UTF-8-using system is tobe read on Windows (orvice versa).

The rest of this paragraph applies iffile is an actualfilename or URL (and not"" nor a connection). Ifencoding = "unknown", an attempt is made to guess the encoding:the result oflocaleToCharset() is used as a guide. Ifencoding has two or more elements, they are tried in turn untilthe file/URL can be read without error in the trial encoding. If anactualencoding is specified (rather than the default or"unknown") in a Latin-1 or UTF-8 locale then character stringsin the result will be translated to the current encoding and marked assuch (seeEncoding).

Iffile is a connection (including one specified by""),it is not possible to re-encode the input insidesource, and sotheencoding argument is just used to mark character strings in theparsed input in Latin-1 and UTF-8 locales: seeparse.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)The New S Language.Wadsworth & Brooks/Cole.

See Also

demo which usessource;eval,parse andscan;options("keep.source").

sys.source which is a streamlined version to source afile into an environment.

‘The R Language Definition’ for a discussion of sourcedirectives.

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})## 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 envwithAutoprint({ x <- 1:2; cat("x=",x,"\n"); 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)

What can we improve?

R Package Documentation

Browse R Packages

We want your feedback!

Note that we can't provide technical support on individual packages. You should contact the package authors for that.

 
Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, readEmbedding Snippets.

Close

[8]ページ先頭

©2009-2026 Movatter.jp