Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings as variable references in an R formula

Tags:

r

R newbie question here. I have a list called dbdata. Normally I use it like this:

myresults <- rlm(V001 ~ V002+V003, data=dbdata)

However, I would like to make these references dynamic. I need to have something like this:

var1 <- "V001"
var2 <- "V002"
var3 <- "V003"
myresults <- rlm(var1 ~ var2+var3, data=dbdata)

How would I reference the variables in the context of rlm()? I thought perhaps something like eval(), but that didn't work.

Thanks!

like image 509
Fugue Avatar asked Sep 22 '10 15:09

Fugue


2 Answers

One solution is to build the formula up using paste() and convert it to a formula:

> ## your example plus some dummy data
> var1 <- "V001"
> var2 <- "V002"
> var3 <- "V003"
> dat <- data.frame(V001 = runif(10), V002 = runif(10), V003 = runif(10))
> f <- formula(paste(var1, "~", var2, "+", var3))

Now we can look at f

> f
V001 ~ V002 + V003
> class(f)
[1] "formula"

and it really is a formula. We can now pass this into rlm() as the first argument:

> require(MASS)
> mod <- rlm(f, data = dat)
> mod
Call:
rlm(formula = f, data = dat)
Converged in 8 iterations

Coefficients:
(Intercept)        V002        V003 
  0.2725538  -0.1281576   0.1617250 

Degrees of freedom: 10 total; 7 residual
Scale estimate: 0.251

HTH

like image 198
Gavin Simpson Avatar answered Sep 19 '22 17:09

Gavin Simpson


You can create formulas based on strings with the reformulate function:

form <- reformulate(c(var2, var3), response = var1)
# V001 ~ V002 + V003

myresults <- rlm(form, data = dbdata)
like image 22
Sven Hohenstein Avatar answered Sep 21 '22 17:09

Sven Hohenstein