0

I am new to R, and am trying to loop regressions by group. For my data I have 13 groups, and would like to create 13 objects--a regression result for each group, so I can put all the regression results in a table. Here is what I have tried:

for (i in 1:13) {groupi = lm(Yvariable ~ Xvariables,
           data = dataset,
           subset = dataset$group== i )}

So that I would have 13 group'i' objects that are each a regression result to put into a table. THANKS!

jonatjano
  • 3,576
  • 1
  • 15
  • 20
  • 1
    try one of the solutions from this post: https://stackoverflow.com/questions/51796317/r-predict-glm-fit-on-each-column-in-data-frame-using-column-index-number/51810814#51810814 – AndS. Jan 11 '19 at 20:40
  • Split your data, then map `lm` over the different subsets to make a list: `values <- lapply(split(dataset, dataset$group), function(grp) {lm(yvar~xvars, data=grp)})` – MrFlick Jan 11 '19 at 21:14
  • see `lme4::lmList()` ? – Ben Bolker Jan 12 '19 at 00:20

2 Answers2

1

If I get your problem right there is a specialised command for this: lmList from the nlme package. Try this:

    library(nlme)
    your.result.list <- lmList(Yvariable ~ Xvariables | group, data = dataset)
    your.result.list

The object your.result.list is of class lmList so it is a list with the 13 elements that you wanted to have as single objects. It has a generic print option which prints you a table of the coefficients into the console. So maybe this is already what you want?

user1966337
  • 115
  • 7
0

Consider by, object-oriented wrapper to tapply, designed to subset data frames by factor(s) and run operations on the subsets. Often it can replace split + lapply for a more streamlined call:

reg_list <- by(dataset, dataset$group, function(sub)
                summary(lm(Yvariable ~ Xvariables,
                           data = sub)
                       )
              )

Please note the above only produces a named list of regression result summaries. Further work is needed for extraction of each model's estimates by extending function.

Parfait
  • 104,375
  • 17
  • 94
  • 125