首页 > 解决方案 > 使用 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))

但是,这是行不通的。请问你能帮帮我吗。

标签: rdplyrregression

解决方案


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))

可能有一个更紧凑的解决方案,我正在试图弄清楚。


推荐阅读