将 %>% 与 lm 和 rbind 一起使用

Using `%>%` with `lm` and `rbind`

我有一个数据框 Z 看起来像

t  x  y  d
0  1  2  1
1  2  3  1
2  3  4  1
0  1  2  2
1  2  3  2
2  3  4  2

其中 d 是一个因子列。我知道想为 d 中的两个因素拟合 lmy 超过 t 的线性模型,并将其作为新列添加到数据框中。

我试过了

Z %>%
  filter(d == 1) %>%
  lm(y ~ t)

但这给了我一个错误 "Error in as.data.frame.default(data) : cannot coerce class ""formula"" to a data.frame"。但是

lm(y ~ t, data = Z)

工作正常。任何帮助将不胜感激。

我们需要提取出data.代表的数据对象

Z %>% 
  filter(d == 1) %>% 
  lm(y ~ t, data = .)
#Call:
#lm(formula = y ~ t, data = .)

#Coefficients:
#(Intercept)            t  
#          2            1  

summarise/mutate/group_by 和其他 tidyverse 函数中,我们可以简单地传递列名。在这里,我们要么需要从数据环境中获取列,要么在 summarise

中创建一个 list 输出
library(magrittr)    
Z %>%
  filter(d ==1 ) %>%
  summarise(lmout = list(lm(y ~ t))) %>%
  pull(lmout) %>%
  extract2(1)
#Call:
#lm(formula = y ~ t)

#Coefficients:
#(Intercept)            t  
#          2            1