[R] R & bash script
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Sat Feb 19 09:53:58 CET 2005
On 18-Feb-05 Christian Schulz wrote:
> how is it possible to use more than one command when i'm
> didn't want use R CMD BATCH for specific reason?
>
> $ echo "(x<-1:10)" | R --vanilla
> works
>
> $ echo "(x<-1:10 ;y<-20:30 ;lm(y ~ x))" | R --vanilla
> works not.
Two things wrong with the above:
1. Use y<-21:30 with x<-1:10 otherwise "variable lengths differ"!
2. While (x<-1:10) returns the value of the assignment, i.e.
[1] 1 2 3 4 5 6 7 8 9 10
(which I suppose you wanted to see, as a check),
even (x<-1:10 ;y<-20:30) is a syntax error in R, and
(x<-1:10 ;y<-20:30 ;lm(y ~ x)) is an even bigger one!
You can emulate completely the typing in of commands by using
the "-e" option to echo, which allows you to use escape
sequences in the string, so that you can insert "\n" where
you would usually press Return. So:
echo -e "(x<-1:10) \n (y<-21:30) \n lm(y~x)" | R --vanilla
will work fine; and here the "(...)" cause R to print out
confirmation of the assignments "x<-1:10" and "y<-1:10"
which normally you perhaps wouldn't want, so the "production"
version of the above would be
echo -e "x<-1:10 \n y<-21:30 \n lm(y~x)" | R --vanilla
> Is it further possible using bash variables like $i from a loop
> in the bash echo call i.e.
> dm$x$i$k <- read.data("dmdata$x$i$k.dat",header=T)
Of course it is, as in
export LIM="10"
echo -e "x<-1:$LIM \n y<-21:30 \n lm(y~x)" | R --vanilla
but just make sure that you escape "$" when you need it
as part of an R syntax, e.g. when accessing named components
of a list. Thus:
echo -e "x<-1:$LIM \n y<-21:30 \n lm(y~x)\$fitted.values" | R --vanilla
Compare with what happens when you don't escape the "$", i.e.
echo -e "x<-1:$LIM \n y<-21:30 \n lm(y~x)$fitted.values" | R --vanilla
You need to take similar precautions for all shell metacharacters
which might occur in an R statement (see "man bash" for these).
Hoping this helps,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 19-Feb-05 Time: 08:53:58
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list