[R] argv[0] --- again
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Apr 3 17:49:22 CEST 2006
On 4/3/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> On 4/2/06, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> > On 4/2/2006 9:34 PM, ivo welch wrote:
> > > dear R group: I have the probably fairly common problem that I would
> > > like to have one code.R file do different things if it is invoked from
> > > a symbolic link, which should be easy to uncover.
> > >
> > > $ ln -s code.R code-0.R
> > > $ ln -s code.R code-1.R
> > > $ R CMD BATCH code-1.R
> > >
> > > what needs to be in code-1.R to put code-1.r into a character vector?
> > > help appreciated.
> > >
> > > regards, /ivo welch
> > >
> > >
> > > PS : I read the past R-help posts on the subject, but apparently
> > > the older suggested solutions no longer work. (commandArgs() is not
> > > the answer, either.) And I did also not see it under the FAQ in the R
> > > programming section...and may I suggest this for the faq?
> >
> > I think the answer to this is platform dependent. In Windows, the
> > answer is: you can't. The command line gets eaten by Rcmd.exe and
> > isn't passed to R.
>
> But you can still get it from the system. On XP Pro
> (maybe other Windows systems too?) place this in a.r
>
> out <- system("wmic /output:stdout process", intern = TRUE)
> out <- sapply(out, function(x) substr(x, 1, nchar(x)-1))
> print(strsplit(grep("rcmd.exe.*batch", tolower(out), value = TRUE), "
> *")[[1]][4])
>
> and then at the command line type:
>
> Rcmd BATCH a.r
>
> and it will print out a.r
>
Here is one other approach. Create a batch file and have that
batch call the R program using the program name as an argument,
which the R program can then extract.
The following uses the fact that lines beginning with rem are
ignored by batch and the if statement happens to work in
both R and batch. This allows us to combine the batch file
and R program in the same file. This works at least on Windows XP.
Place the following in a file called a.bat, say, and then at the
Windows command line issue the command: a.bat
a.bat will run as a batch file and then call itself as an R program
passing its name to the R program in the argument list:
rem <- 3
if (rem == 3) 0 else goto:batch
# R code goes here
args <- commandArgs()
prog <- sub("-", "", grep("^-[^-]", args, value = TRUE))
print(prog)
q("no")
:batch
:: batch code goes here
Rcmd BATCH -%0 %0
More information about the R-help
mailing list