Programatically Create Formulas in R
January 17, 2023
I’m working on a prototype of a tool using R to create some regressions. I’d like to take in independent and dependent variables as character vectors and use those to create a formula. It took me a minute to figure out how to programatically create a formula. It’s a bit tricky because formula require unquoted objects (symbols).
The trick is to use the function reformulate() (thanks
StackOverflow).
The syntax is reformulate(x_vars, y_var)
form <-
form
y ~ x1 + x2
Nice. Throw it into a function.
{
form <-
}
Now try it out :)
Call:
lm(formula = form, data = .data)
Coefficients:
(Intercept) Sepal.Length Petal.Length
-0.008996 -0.082218 0.449376
This can be a pretty hand pattern in package development. I hope it helps you.