r - 使用 dplyr 存储回归的输出
问题描述
df.h <- data.frame(
hour = factor(rep(1:24, each = 21)),
price = runif(504, min = -10, max = 125),
wind = runif(504, min = 0, max = 2500),
temp = runif(504, min = - 10, max = 25))
如果我想对价格对风和价格对温度进行线性回归,我可以这样做:
df.h %>% group_by(hour) %>% do(mod1 = lm(price ~ wind , data = .),
mod2 = lm(price ~ temp, data = .))
但是,我想要的是提取 mod1 和 mod2 的残差并将残差存储为两个附加列
df.h %>% group_by(hour) %>%
do(mod1 = lm(price ~ wind , data = .),
mod2 = lm(price ~ temp, data = .)) %>%
mutate(mod1.resid = resid(mod1),
mod2.resid = resid(mod2))
但是,这是行不通的。请问你能帮帮我吗。
解决方案
mod <- df.h %>% group_by(hour) %>% do(mod1 = resid(lm(price ~ wind , data = .)),
mod2 = resid(lm(price ~ temp, data = .)))
df.h <- df.h %>%
mutate(res1 = unlist(mod$mod1),
res2 = unlist(mod$mod2))
可能有一个更紧凑的解决方案,我正在试图弄清楚。
推荐阅读
- jquery - Chrome 在网站加载时抛出混合内容错误
- ubuntu - Ubuntu NVIDIA 驱动程序更改现在不会启动到 Unity
- xcode - 断点命中时辅助编辑器中的文件跳转到主编辑器(Xcode)
- scala - 是什么让 scala 中的类/特征成为 ADT
- html - 如何动态填充列表视图编辑模板列表项值 (asp)?
- android - Tizen Web 应用程序上的手机电池状态
- jsonschema - 使用 Json Schema 的 AJV 修改数据
- javascript - 优化我的功能
- javascript - 递归循环对象树
- javascript - 如何根据数据d3js设置最初确定的缩放级别