[R] using var from bash in R script
marc_schwartz at me.com
Wed Jan 4 23:00:00 CET 2012
On Jan 4, 2012, at 3:08 PM, dood wrote:
> Dear R users,
> This probably a really noob question, but I'm stuck. I'd like to pass some
> variables from bash to R as strings. I can successfully pass variables using
> commandArgs(), the problem is that I end up with an array. So, for example:
>> Args <- commandArgs(TRUE)
>  "one" "two" "three"
> Now, it just so happens that "one", "two", "three" are names of columns that
> I'd like to work with. I'd like to do something like this:
>> print(summary(lm(Args ~ Args)))
> But, this doesn't work. The alternative would be to let bash write a number
> of R-scripts and then rm them when done, but that seems like an unnecessary
> Can this be done?
See ?as.formula and ?paste
Something along the lines of the following should work:
Args <- c("one", "two", "three")
 "one" "two" "three"
> paste(Args, "~", Args)
 "one ~ two"
> as.formula(paste(Args, "~", Args))
one ~ two
summary(lm(as.formula(paste(Args, "~", Args))))
If 'one', 'two' and 'three' are columns in a data frame (say 'DF'), you will want to use the data argument in the call to lm():
summary(lm(as.formula(paste(Args, "~", Args)), data = DF))
More information about the R-help