r - 按组回归并保留R中的所有列
问题描述
我正在按组进行线性回归,并希望提取回归的残差
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
来绑定ID, ID2
和augment
输出使用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>
推荐阅读
- android - Android / Gradle:是否可以在我的源集中创建多个可绘制目录?
- angular - 如何将多个参数传递给隐藏属性?
- c# - 使用 NEST 使用弹性搜索对多种类型进行排序
- android - android 9 上的过滤扫描不会使用 UUID 过滤器找到信标
- javascript - onclick 还会重定向到“表单操作”
- python - 关于形状未对齐反向传播的错误
- python - 我收到 ValueError:无法将字符串转换为浮点数。任何人都可以编辑这个吗?
- wordpress - 在子目录中安装 Wordpress 作为插件域并删除 url 中的安装文件夹
- laravel - Laravel 速率限制会记住 X-Ratelimit-Remaining 来自其他节流路由 - 导致错误的请求过多
- java - 在注解处理器中使用 JavaPoet 编写 java 文件