Home > Back-end >  using lm function in R with a variable name in a loop
using lm function in R with a variable name in a loop

Time:11-16

I am trying to create a simple linear model in R a for loop where one of the variables will be specified as a parameter and thus looped through, creating a different model for each pass of the loop. The following does NOT work:

   model <- lm(test_par[i] ~ weeks, data=all_data_plant)

If I tried the same model with the "test_par[i]" replaced with the variable's explicit name, it works just as expected:

   model <- lm(weight_dry ~ weeks, data=all_data_plant)

I tried reformulate and paste ineffectively. Any thoughts?

CodePudding user response:

Maybe try something like this:

n <-   #add the column position of first variable
m <-   #add the column position of last variable

lm_models <- lapply(n:m, function(x) lm(all_data_plant[,x] ~ weeks, data=all_data_plant))

CodePudding user response:

You can pass the argument "formula" in lm() as character using paste(). Here a working example:

data("trees")
test_par <- names(trees)

model <- lm(Girth ~ Height, data = trees)
model <- lm("Girth ~ Height", data = trees)  # character formula works
model <- lm(paste(test_par[1], "~ Height"), data=trees)
  •  Tags:  
  • r
  • Related