R与群体的回归

时间:2016-05-18 00:55:30

标签: r loops regression linear-regression

我导入了一个包含3列的CSV,用于Y和X的2列,以及用于标识X的类别的第三列(我有20个组/类别)。我能够在整体水平上运行回归,但我想分别对20个类别运行回归并存储co-efs。

我尝试了以下内容:

list2env(split(sample, sample$CATEGORY_DESC), envir = .GlobalEnv)

现在我有20个文件,如何在这20个文件上运行回归并将co-effs存储在某个地方。

3 个答案:

答案 0 :(得分:3)

由于没有提供数据,我正在生成一些示例数据,以展示如何使用dplyrbroom包运行多个回归并存储输出。

在下文中,每组有20组和不同的x / y值。运行20次回归,并将这些回归的输出作为数据框提供:

library(dplyr)
library(broom)
df <- data.frame(group = rep(1:20, 10),
                 x = rep(1:20, 10) + rnorm(200),
                 y = rep(1:20, 10) + rnorm(200))
df %>% group_by(group) %>% do(tidy(lm(x ~ y, data = .)))

示例输出:

Source: local data frame [40 x 6]
Groups: group [20]

   group        term    estimate std.error  statistic     p.value
   <int>       <chr>       <dbl>     <dbl>      <dbl>       <dbl>
1      1 (Intercept)  0.42679228 1.0110422  0.4221310 0.684045203
2      1           y  0.45625124 0.7913256  0.5765657 0.580089051
3      2 (Intercept)  1.99367392 0.4731639  4.2134955 0.002941805
4      2           y  0.05101438 0.1909607  0.2671460 0.796114398
5      3 (Intercept)  3.14391308 0.8417638  3.7349114 0.005747126
6      3           y  0.08418715 0.2453441  0.3431391 0.740336702

答案 1 :(得分:2)

使用lmList快速解决方案(包nlme):

library(nlme)
lmList(x ~ y | group, data=df)

    Call:
  Model: x ~ y | group 
   Data: df 

Coefficients:
   (Intercept)           y
1    0.4786373  0.04978624
2    3.5125369 -0.94751894
3    2.7429958 -0.01208329
4   -5.2231576  2.24589181
5    5.6370824 -0.24223131
6    7.1785581 -0.08077726
7    8.2060808 -0.18283134
8    8.9072851 -0.13090764
9   10.1974577 -0.18514527
10   6.0687105  0.37396911
11   9.0682622  0.23469187
12  15.1081915 -0.29234452
13  17.3147636 -0.30306692
14  13.1352411  0.05873189
15   6.4006623  0.57619151
16  25.4454182 -0.59535396
17  22.0231916 -0.30073768
18  27.7317267 -0.54651597
19  10.9689733  0.45280604
20  23.3495704 -0.14488522

Degrees of freedom: 200 total; 160 residual
Residual standard error: 0.9536226

从@Gopala回答借用数据df。

答案 2 :(得分:0)

还考虑使用lapply()

的基本解决方案
regressionList <- lapply(unique(df$group),
                         function(x) lm(x ~ y, df[df$group==x,]))

只有系数:

coeffList <- lapply(unique(df$group),
                    function(x) lm(x ~ y, df[df$group==x,])$coefficients)

甚至摘要列表:

summaryList <- lapply(unique(df$group),
                      function(x) summary(lm(x ~ y, df[df$group==x,])))