【问题标题】:Using dplyr to store the output of regression使用 dplyr 存储回归的输出
【发布时间】:2018-06-28 12:23:47
【问题描述】:
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))

但是,这不起作用。请问你能帮帮我吗。

【问题讨论】:

  • 您可能对broom 包感兴趣,请参阅之前“使用 tidiers 进行可视化与 ggplot2”标题的示例。

标签: r dplyr regression


【解决方案1】:
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))

可能有一个更紧凑的解决方案,我正在尝试找出。

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 2016-10-14
    • 2019-08-17
    • 2022-01-12
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多