How do you use variables in a regression formula in R? -


how use variable in regression formula?

for example, using 'animals' dataset (in mass), following works fine:

data(animals) model <- lm(body ~ brain, data = animals) 

but want is:

data(animals) x <- "body" y <- "brain" model <- lm(x ~ y, data = animals) 

this doesn't work, can't figure out need do. ultimately, i'm trying put formula inside loop , have run different each time.

sorry if answer obvious - i've searched can't solve it.

many thanks

you need make proper formula character values. easiest way in case reformulate() function

reformulate(y,x) # body ~ brain 

then can use in lm() call

lm(reformulate(y,x), data = animals) #  # call: # lm(formula = reformulate(y, x), data = animals) #  # coefficients: # (intercept)        brain   #  4316.32258     -0.06594   

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -