2016-08-20 125 views
-3

我是R新手,但我需要针对不同ID使用面板数据运行几个简单回归。 我有4列1. ID 2.时间3. Y 4. X和我需要回归Y〜X为每个ID。我有100个ID,每个ID有120个时间段,所以我需要用120个观测值运行100个简单回归。在R中使用面板数据在不同ID中运行多个回归

我该怎么办呢?

非常感谢您提前!

回答

2

我们既可以使用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 
+0

非常感谢您!唯一的问题是我的R无法找到浏览功能。它是否在我可能没有安装的pacage中? – Beatrice

+0

@Beatrice'glance'来自'库(扫帚)'如果你没有安装它,'install.packages(“扫帚”)'然后加载'库(扫帚)' – akrun

+1

非常感谢你!我会马上尝试! – Beatrice

1

的NLME封装具有lmList

library(nlme) 
fm <- lmList(Y ~ X | ID, DF, pool = FALSE) 

或使用pool = TRUE(默认值)如果您想要共同的汇总方差。还请查看这些在"lmList"类对象上运行的方法:

methods(class = "lmList") 
+0

谢谢你,我试过像你说的,但是,我怎样才能得出与系数相关的pvalues?谢谢! – Beatrice

+0

尝试'摘要(fm)' –

+0

我试过了,但没有显示pvalues! – Beatrice