Pass a vector of variables into lm() formula

Anand picture Anand · Feb 11, 2012 · Viewed 44.8k times · Source

I was trying to automate a piece of my code so that programming become less tedious.

Basically I was trying to do a stepwise selection of variables using fastbw() in the rms package. I would like to pass the list of variables selected by fastbw() into a formula as y ~ x1+x2+x3, "x1" "x2" "x3" being the list of variables selected by fastbw()

Here is the code I tried and did not work

olsOAW0.r060 <- ols(roll_pct~byoy+trans_YoY+change18m, 
                    subset= helper=="POPNOAW0_r060", 
                    na.action = na.exclude, 
                    data = modelready)

OAW0 <- fastbw(olsOAW0.r060, rule="p", type="residual", sls= 0.05)

vec <- as.vector(OAW0$names.kept, mode="any")

b <- paste(vec, sep ="+") ##I even tried b <- paste(OAW0$names.kept, sep="+")

bestp.OAW0.r060 <- lm(roll_pct ~ b , 
                      data = modelready, 
                      subset = helper =="POPNOAW0_r060",    
                      na.action = na.exclude)

I am new to R and still haven't trailed the steep learning curve, so apologize for obvious programming blunders.

Answer

joran picture joran · Feb 11, 2012

You're almost there. You just have to paste the entire formula together, something like this:

paste("roll_pct ~ ",b,sep = "")

coerce it to an actual formula using as.formula and then pass that to lm. Technically, I think lm may coerce a character string itself, but coercing it yourself is generally safer. (Some functions that expect formulas won't do the coercion for you, others will.)