按组回归并保留R中的所有列

标签 r dplyr regression

我正在按组进行线性回归,并希望提取回归的残差

library(dplyr)
set.seed(124)

dat <- data.frame(ID = sample(111:503, 18576, replace = T), 
                  ID2 = sample(11:50, 18576, replace = T), 
                  ID3 = sample(1:14, 18576, replace = T),
                  yearRef = sample(1998:2014, 18576, replace = T),
                  value = rnorm(18576))


resid <- dat %>% dplyr::group_by(ID3) %>% 
         do(augment(lm(value ~ yearRef, data=.))) %>% ungroup()

如何保留 ID , ID2以及 resid .目前只保留ID3在最终的数据框中

最佳答案

使用group_split然后使用 map_dfr 遍历每个组绑定(bind)ID, ID2augment使用 bind_cols 输出

library(dplyr)
library(purrr)
dat %>% group_split(ID3) %>% 
   map_dfr(~bind_cols(select(.x,ID,ID2), augment(lm(value~yearRef, data=.x))), .id = "ID3")

# A tibble: 18,576 x 12
   ID3      ID   ID2   value yearRef .fitted .se.fit   .resid    .hat .sigma .cooksd
   <chr> <int> <int>   <dbl>   <int>   <dbl>   <dbl>    <dbl>   <dbl>  <dbl>   <dbl>
 1 1       196    16 -0.385     2009 -0.0406  0.0308 -0.344   1.00e-3  0.973 6.27e-5
 2 1       372    47 -0.793     2012 -0.0676  0.0414 -0.726   1.81e-3  0.973 5.05e-4
 3 1       470    15 -0.496     2011 -0.0586  0.0374 -0.438   1.48e-3  0.973 1.50e-4
 4 1       242    40 -1.13      2010 -0.0496  0.0338 -1.08    1.21e-3  0.973 7.54e-4
 5 1       471    34  1.28      2006 -0.0135  0.0262  1.29    7.26e-4  0.972 6.39e-4
 6 1       434    35 -1.09      1998  0.0586  0.0496 -1.15    2.61e-3  0.973 1.82e-3
 7 1       467    45 -0.0663    2011 -0.0586  0.0374 -0.00769 1.48e-3  0.973 4.64e-8
 8 1       334    27 -1.37      2003  0.0135  0.0305 -1.38    9.86e-4  0.972 9.92e-4
 9 1       186    25 -0.0195    2003  0.0135  0.0305 -0.0331  9.86e-4  0.973 5.71e-7
10 1       114    34  1.09      2014 -0.0857  0.0500  1.18    2.64e-3  0.973 1.94e-3
# ... with 18,566 more rows, and 1 more variable: .std.resid <dbl>

关于按组回归并保留R中的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996398/

相关文章:

r - 如何根据 R 中的另一个现有表导出百分位数

r - dplyr + magrittr + qplot = 没有情节?

删除字符串 R 数据帧之后出现的行

r - 如何将非数字变量列转换为两个数字变量列?

python - Scikit 学习 : How can I set the SVM Output range in regression?

R data.table 使用 lapply 创建自定义函数来创建和重新分配多个变量

r - 如何在R中的一行中打印文本和变量

regression - 使用 GLM 进行逻辑回归

R/PLM : Cannot estimate random effects model due to error (system is computationally singular)?

RStudio Server 与 opencpu.org 用于自己软件包的基于 Web 的 GUI?