All of the solutions below use the following definitions:
depVars <- c("mpg", "disp") indepVars <- c("qsec", "wt", "drat")
1) character string formula Create a character string representing the formula, and then run lm using do.call . Please note that the formula shown in the output is displayed correctly and is written out.
fo <- sprintf("cbind(%s) ~ %s", toString(depVars), paste(indepVars, collapse = "+")) do.call("lm", list(fo, quote(mtcars)))
giving:
Call: lm(formula = "cbind(mpg, disp) ~ qsec+wt+drat", data = mtcars) Coefficients: mpg disp (Intercept) 11.3945 452.3407 qsec 0.9462 -20.3504 wt -4.3978 89.9782 drat 1.6561 -41.1148
1a) This will also work:
fo <- sprintf("cbind(%s) ~.", toString(depVars)) do.call("lm", list(fo, quote(mtcars[c(depVars, indepVars)])))
giving:
Call: lm(formula = cbind(mpg, disp) ~ qsec + wt + drat, data = mtcars[c(depVars, indepVars)]) Coefficients: mpg disp (Intercept) 11.3945 452.3407 qsec 0.9462 -20.3504 wt -4.3978 89.9782 drat 1.6561 -41.1148
2) reformulate @akrun and @Konrad, suggest using reformulate in the comments below the question. This approach creates a "formula" object, while those above create a string of characters as a formula. (If it was necessary for the previous solutions above, this would be possible using fo <- formula(fo) .) Note that it is important that the reformulate response reformulate be a call object and not a character string, or reformulate interprets the character string as name of one variable.
fo <- reformulate(indepVars, parse(text = sprintf("cbind(%s)", toString(depVars)))[[1]]) do.call("lm", list(fo, quote(mtcars)))
giving:
Call: lm(formula = cbind(mpg, disp) ~ qsec + wt + drat, data = mtcars) Coefficients: mpg disp (Intercept) 11.3945 452.3407 qsec 0.9462 -20.3504 wt -4.3978 89.9782 drat 1.6561 -41.1148
3) lm.fit Another way that does not use the formula at all:
m <- as.matrix(mtcars) fit <- lm.fit(cbind(1, m[, indepVars]), m[, depVars])
The output is a list with these components:
> names(fit) [1] "coefficients" "residuals" "effects" "rank" [5] "fitted.values" "assign" "qr" "df.residual"