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!
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With