我是R新手,但我需要针对不同ID使用面板数据运行几个简单回归。 我有4列1. ID 2.时间3. Y 4. X和我需要回归Y〜X为每个ID。我有100个ID,每个ID有120个时间段,所以我需要用120个观测值运行100个简单回归。在R中使用面板数据在不同ID中运行多个回归
我该怎么办呢?
非常感谢您提前!
我是R新手,但我需要针对不同ID使用面板数据运行几个简单回归。 我有4列1. ID 2.时间3. Y 4. X和我需要回归Y〜X为每个ID。我有100个ID,每个ID有120个时间段,所以我需要用120个观测值运行100个简单回归。在R中使用面板数据在不同ID中运行多个回归
我该怎么办呢?
非常感谢您提前!
我们既可以使用data.table
library(data.table)
setDT(df1)[, coef(lm(Y~X)), by = ID]
或者如果我们使用broom
,那么我们就可以得到输出
library(broom)
setDT(df1)[, glance(lm(Y~X)), Species]
pvalues
setDT(df1)[, summary(lm(Y~X))$coef[,4], by = ID]
或用broom/dplyr
library(dplyr)
df1 %>%
group_by(ID) %>%
do(model = lm(Y~X, .)) %>%
glance(model)
重现性实施例
data(iris)
iris %>%
group_by(Species) %>%
do(model = lm(Sepal.Width ~Petal.Width, .)) %>%
glance(model)
# Species r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual
# <fctr> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <dbl> <int>
#1 setosa 0.0541735 0.03446878 0.3724741 2.749265 1.038211e-01 2 -20.546993 47.093987 52.830056 6.659375 48
#2 versicolor 0.4408943 0.42924626 0.2370691 37.851387 1.466661e-07 2 2.043799 1.912403 7.648472 2.697685 48
#3 virginica 0.2891514 0.27434209 0.2747206 19.524930 5.647610e-05 2 -5.326334 16.652669 22.388738 3.622626 48
并用data.table/broom
as.data.table(iris)[, glance(lm(Sepal.Width~Petal.Width)), by = Species]
# Species r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual
#1: setosa 0.0541735 0.03446878 0.3724741 2.749265 1.038211e-01 2 -20.546993 47.093987 52.830056 6.659375 48
#2: versicolor 0.4408943 0.42924626 0.2370691 37.851387 1.466661e-07 2 2.043799 1.912403 7.648472 2.697685 48
#3: virginica 0.2891514 0.27434209 0.2747206 19.524930 5.647610e-05 2 -5.326334 16.652669 22.388738 3.622626 48
非常感谢您!唯一的问题是我的R无法找到浏览功能。它是否在我可能没有安装的pacage中? – Beatrice
@Beatrice'glance'来自'库(扫帚)'如果你没有安装它,'install.packages(“扫帚”)'然后加载'库(扫帚)' – akrun
非常感谢你!我会马上尝试! – Beatrice