简体   繁体   English

在 R 中按组重复回归

[英]Repeat regression by group in R

I have 50 countries in a data frame and want to repeat the same regression model 50 times for each country.我在一个数据框中有 50 个国家,并且想为每个国家重复相同的回归 model 50 次。 I have a column for country IDs:我有一列国家 ID:

enter image description here在此处输入图像描述

Since I am analyzing imputed datasets, I am using "with" and "implist."由于我正在分析估算数据集,因此我使用“with”和“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?如何为每个国家/地区重复此 model 50 次并查看每个国家/地区的收入和年龄系数? I can split data to each country if it is more convenient.如果更方便,我可以将数据拆分到每个国家/地区。 Any ways will be fine for me.任何方式对我来说都很好。 Thank you in advance.先感谢您。

I believe that there is a fancy tydiverse approach, but in base R that might work (can't test it without data):我相信有一种花哨的 tydiverse 方法,但在基础 R 可能有效(没有数据无法测试):

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)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM