如何在 dplyr 的 do() 输出上使用 coef()

How to use coef() on output of do() from dplyr

我的问题 几乎dplyr 0.3.0.9000 how to use do() correctly 中得到了回答,但不完全是。

我有一些数据如下所示:

> head(myData)
   Sequence Index  xSamples ySamples
6         0     5 0.3316187 3.244171
7         0     6 1.5131778 2.719893
8         0     7 1.9088933 3.122991
9         0     8 2.7940244 3.616815
10        0     9 3.6500311 3.519641

Sequence 的实际范围是 0 到 9999。在每个 Sequence 中,xSamples 和 ySamples 都应该与 Index 成线性关系。计划是按序列对 myData 进行分组,然后在每个组上通过 do() 使用 lm()。代码是这样的(无耻地从帮助中提取):

library(dplyr)
myData_by_sequence <- group_by(myData, Sequence)
models <- myData_by_sequence %>% do(mod = lm(xSamples ~ Index, data = .))

这行得通,但我得到的结果是这样的。 . .

> head(models)
Source: local data frame [10000 x 2]

  Sequence     mod
1        0 <S3:lm>
2        1 <S3:lm>
3        2 <S3:lm>
4        3 <S3:lm>
5        4 <S3:lm>
6        5 <S3:lm>

。 . .我想要的数据卡在第二列中。我有一个有效的 plyr 解决方案,它是这样的。 . .

models <- dlply(myData, "Sequence", function(df) lm(xSamples ~ Index, data = df))
xresult <- ldply(models, coef)

。 . .由于 coef(),这给了我分解成数据框的结果。问题是我不能将 dplyr(我通常使用和喜爱)与 plyr 混合使用,而且我似乎无法 coef() 使用 dplyr 输出的第二列。

我尝试了一些其他方法,例如尝试将 coef()lm() 步骤结合起来,我可以将第二列分解为线性模型列表,但我不能'不要在列表中使用 do()

我真的觉得我在这里遗漏了一些明显的东西。 R 绝对不是我的主要语言。任何帮助将不胜感激。

编辑 试过 。 . .

result <-
    rects %>% 
    group_by(Sequence) %>% 
    do(data.frame(Coef = coef(lm(xSamples ~ Frame, data = .))))

。 . .并得到非常接近的东西,但系数堆叠在同一列中:

  Sequence       Coef
1        0 -5.0189823
2        0  1.0004240
3        1 -4.9411745
4        1  0.9981858

尝试

library(dplyr) 
myData %>%
      group_by(Sequence) %>%
      do(data.frame(setNames(as.list(coef(lm(xSamples~Index, data=.))),
                 c('Intercept', 'Index')))
#    Sequence Intercept     Index
#1        0 -3.502821 0.7917671
#2        1  3.071611 0.3226020

或使用data.table

 library(data.table)
 setDT(myData)[, as.list(coef(lm(xSamples~Index))) , by = Sequence]
 #   Sequence (Intercept)     Index
 #1:        0   -3.502821 0.7917671
 #2:        1    3.071611 0.3226020

数据

 myData <- structure(list(Sequence = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L,
 1L, 1L), Index = c(5L, 6L, 7L, 8L, 9L, 15L, 6L, 9L, 6L, 10L),
 xSamples = c(0.3316187, 
 1.5131778, 1.9088933, 2.7940244, 3.6500311, 7.3316187, 4.5131778, 
 9.9088933, 3.7940244, 4.6500311), ySamples = c(3.244171, 2.719893, 
 3.122991, 3.616815, 3.519641, 3.244171, 8.719893, 5.122991, 7.616815, 
 5.519641)), .Names = c("Sequence", "Index", "xSamples", "ySamples"
 ), class = "data.frame", row.names = c(NA, -10L))