在管道 (%>%) 流中执行 lm():模型公式中的无效项错误

perform lm() inside a piped (%>%) flow: Error of invalid term in model formula

我打算按 data.frame 中的每个因素水平进行单独回归。我以前可以使用 plyr::ddply 来做到这一点。但是,当我尝试使用管道流分析时,遇到了如下错误。请告知如何克服它,否则我将不得不恢复到 plyr::ddply 等。谢谢。

d = data.frame(
Gender = c("M","F"),
Age = rnorm(20, mean = 40, sd = 3),
Weight = rnorm(20, mean=70, sd=5)
)


fit <- d %>% group_by(Gender) %>%
summarise(
  Intercept = coef(lm(Weight ~ Age))[1],
  Slope = coef(lm(Weight ~ Age))[2]
)

Error: invalid term in model formula

使用 do 会有所帮助,模型只会计算一次:

fit <- d %>% group_by(Gender) %>% 
       do(model = lm(Weight ~ Age, data=.)) %>% 
       mutate(Intercept=coef(model)[1], Slope=coef(model)[2]) %>%
       select(-model)

省略最后一个 select(-model) 以将您的 lm 模型保留在它们自己的列中。

更简单的解决方案甚至是使用 broombroom::tidy 将模型输出重新排列为漂亮干净的数据帧,您无需手动访问各个系数。有关详细信息,请参阅 vignette(broom)

library(dplyr)
library(broom)

fit <- d %>% group_by(Gender) %>% do(data.frame(tidy(lm(Weight ~ Age, data=.))))
fit
Source: local data frame [4 x 6]
Groups: Gender [2]

  Gender        term   estimate  std.error  statistic     p.value
  (fctr)       (chr)      (dbl)      (dbl)      (dbl)       (dbl)
1      F (Intercept) 92.5751034 37.6736331  2.4572916 0.039485169
2      F         Age -0.5132374  0.9098960 -0.5640616 0.588172020
3      M (Intercept) 41.4985927 10.4958042  3.9538269 0.004213341
4      M         Age  0.7346306  0.2691001  2.7299529 0.025847680

此处,模型输出根据分组变量存储,每个系数存储在单独的行中,您可以轻松地对其进行子集化。