Timm S.
Timm S.

Reputation: 5435

R / lm: Named variables instead of formulas?

Is it possible to hand over the elements of a very basic linear model to the lm() function as variables instead of a formula? I.e. instead of

lin_mod <- lm(Sepal.Length ~ Sepal.Width, data = iris) 

something like this:

lin_mod <- lm(x = Sepal.Width, y = Sepal.Length, data = iris)

Background: I know I can hand over variables to formulas via paste(), but this gets tricky when working with multiple variable handovers inside functions. In the end, I would like to be able to use curly bracket variable handover in lm()

Upvotes: 1

Views: 58

Answers (1)

akrun
akrun

Reputation: 887911

We can use reformulate and passs that inside lm

lm(reformulate('Sepal.Width', response = 'Sepal.Length'), data = iris)
#Call:
#lm(formula = reformulate("Sepal.Width", response = "Sepal.Length"), 
    data = iris)

#Coefficients:
#(Intercept)  Sepal.Width  
#     6.5262      -0.2234  

Upvotes: 1

Related Questions