Home > Enterprise >  Repeat regression by group in R
Repeat regression by group in R

Time:09-23

I have 50 countries in a data frame and want to repeat the same regression model 50 times for each country. I have a column for country IDs:

enter image description here

Since I am analyzing imputed datasets, I am using "with" and "implist." For example,

model <- with(implist, lmer(happy~income age sex education city
                     (1|school))

How can I repeat this model 50 times for each country and see the coefficients of income and age for each country? I can split data to each country if it is more convenient. Any ways will be fine for me. Thank you in advance.

CodePudding user response:

I believe that there is a fancy tydiverse approach, but in base R that might work (can't test it without data):

perform.regression = function(a.country, implist){
  sub.implist = subset(implist, country == a.country)
  one.model = with(sub.implist, lmer(happy~income age sex education city
                                      (1|school)) 
  return(one.model$coefficients)
}
countries = unique(implist$countries)
sapply(countries, perform.regression, implist = implist)

CodePudding user response:

I would probably do something like this. As stated by others, it is difficult to help without any data:

library(tidyverse)


implist |>
  nest(data = -country) |>
  mutate(model = map(data, ~lmer(happy~income age sex education city (1|school),
                                 data = .x)),
         tidied = map(model, broom::tidy))|>
  unnest(tidied)
  • Related