[R] Is a .R script file name available inside the script?

Gabor Grothendieck ggrothendieck at gmail.com
Thu Apr 7 03:56:08 CEST 2005


It works for me.  Suppose in.txt is a two line file with these two lines:

file <- "Rscript.R"
source(file)

and Rscript.R is a two line file with these two lines:

script.description <- function() eval.parent(quote(file), n = 3)
print(basename(script.description()))

Then here is the output on Windows:

C:\Program Files\R\rw2001beta\bin>R --vanilla < in.txt

R : Copyright 2004, The R Foundation for Statistical Computing
[snip]
> file <- "Rscript.R"
> source(file)
[1] "Rscript.R"

Note that 'file' referred to in 'eval.parent' is not the variable that
you called 'file' but is an internal variable within the 'source'
program that is called 'file'.  It has nothing to do with your 'file',
which very well could have a different name.  In fact you
just do this on Windows:

  echo source("Rscript.R")  | R --vanilla

From:   Darren Weber <darrenleeweber at gmail.com>

That is useful, when calling the script like this:

> file <- "Rscript.R"
> source(file)

However, it does not work if we do this from the shell prompt:

$ R --vanilla < Rscript.R

because the eval.parent statement attempts to access a "base
workspace"that does not contain the "file" object/variable, as above.
Isthere a solution for this situation?  Is the input script file
anargument to R and therefore available in something like argv?

On Mar 18, 2005 8:00 PM, Gabor Grothendieck <ggrothendieck at myway.com> wrote:
Darren Weber <darrenleeweber <at> gmail.com> writes:

:
: Hi,
:
: if we have a file called Rscript.R that contains the following, for example:
:
: x <- 1:100
: outfile = "Rscript.Rout"
: sink(outfile)
: print(x)
:
: and then we run
:
: >> source("Rscript.R")
:
: we get an output file called Rscript.Rout - great!
:
: Is there an internal variable, something like .Platform, that holds
: the script name when it is being executed?  I would like to use that
: variable to define the output file name.
:

In R 2.0.1 try putting this in a file and sourcing it.

script.description <- function() eval.parent(quote(file), n = 3)
print(basename(script.description()))

If you are using R 2.1.0 (devel) then use this instead:

script.description <- function()
       showConnections() [as.character(eval.parent(quote(file), n = 3)),
               "description"]
print((basename(script.description())))




More information about the R-help mailing list