extract predictors from formulas

Viewed 44

Suppose that we have a linear model fitted by

lm1 <- lm(mpg ~ sin(2 * pi * wt), data = mtcars)

Is there a way to figure out from lm1 and mtcars that the predictor that is in lm1 is wt (instead of sin(2 * pi * wt))?

2 Answers

We may use all.vars on the formula

all.vars(lm1$call[[2]])[3]
[1] "wt"

Or with get_all_vars

names(get_all_vars(lm1$call$formula, mtcars))[3]
[1] "wt"

You could also use rsample::form_pred() (or all.vars() directly and subset like the answer above):

lm1 |> terms() |> rsample::form_pred()

As pi is built-in constant (and one of the only ones in R), a more general solution would remove this:

 terms <- lm1 |> terms() |> all.vars()
 terms[terms != "pi"][-1]

https://stat.ethz.ch/R-manual/R-devel/library/base/html/Constants.html

Related