[R] Standard input and R

Jon Clayden jon.clayden at gmail.com
Thu Jan 3 12:49:22 CET 2008

For what it's worth, I have found one way to achieve what I want,
which is to use "expect", which is installed on many *nix systems. In
case this is useful to anyone else I'm posting a quick example...

$ expect -f test.expect
[1] 7
1: yes
[1] "Answer was yes"
$ cat test.expect
log_user 0
spawn R --quiet --vanilla
set timeout 2
send "print(3+4)\n"
send "source('test.R'); q()\n"
expect -re ">.+\r\n"
interact {
   -re ">.+\r\n"   {}
$ cat test.R
ans <- scan(what=character(0),nlines=1,quiet=T)
print(paste('Answer was',ans))

Thus, I can retain interactivity whilst giving specific "set-up"
commands to R beforehand (in this toy example, just "print(3+4)").
Meanwhile, I avoid trampling on user startup files (i.e. ".Rprofile")
and I don't have to load the default packages manually.

I would still suggest that getting R itself to do this -- most likely
by changing the behaviour of the "-e" option to match that of ruby,
perl and others -- would be very helpful (though I appreciate it may
not be simple).

Alternative suggestions are still welcome, of course.


On 19/12/2007, Jon Clayden <j.clayden at ucl.ac.uk> wrote:
> Dear all,
> I am trying to wrap a *nix shell script around R for a particular
> purpose, for which I need to get R to execute predetermined commands
> but retain interactivity and allow user input during their execution.
> A straight redirection of standard input is therefore not appropriate,
> and I don't think "littler" is the solution because I don't want to
> write an independent R script.
> What I want is effectively something like what ruby does with the '-e'
> option:
> $ ruby -e 'gets'
> <waits for input from terminal>
> R seems to accept an '-e' option too, even though I can't see it
> mentioned in the output from 'R -h', but it doesn't work the same:
> $ R --slave --vanilla -e 'scan(what=character(0),nlines=1,quiet=T)'
> character(0)
> $
> The only way I can get this to work is by creating an .Rprofile file
> containing the commands I want to run, but this is suboptimal for a
> number of reasons: I have difficulties if an .Rprofile already exists
> in the working directory, the default packages are not loaded, and the
> process doesn't quit if stop() is called.
> I have a vague inkling that this may be achievable with a
> pseudoterminal (pty) or named pipe, but if anyone knows a simpler
> route I'd be glad to avoid getting involved in that kind of thing...
> Many thanks in advance.
> Jon
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list