Pass a vector of variables into lm() formula

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.)


You would actually need to use collapse instead of seb when defining b.

b <- paste(OAW0$names.kept, collapse="+")

Then you can put it in joran answer

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

or just use:

paste("roll_pct ~ ",paste(OAW0$names.kept, collapse="+"),sep = "")

I ran into similar issue today, if you want to make it even more generic where you don't even have to have fixed class name, you can use

frmla <- as.formula(paste(colnames(modelready)[1], paste(colnames(modelready)[2:ncol(modelready)], sep = "", 
                              collapse = " + "), sep = " ~ "))

This assumes that you have class variable or the dependent variable in the first column but indexing can be easily switched to last column as:

frmla <- as.formula(paste(colnames(modelready)[ncol(modelready)], paste(colnames(modelready)[1:(ncol(modelready)-1)], sep = "", 
                              collapse = " + "), sep = " ~ "))

Then continue with lm using:

bestp.OAW0.r060 <- lm(frmla , data = modelready, ... )

Tags:

R

Paste

Lm