我有一个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
Run Code Online (Sandbox Code Playgroud)
与d作为一个因子列。我知道要适应线性模型lm,以y超过t两个因素d,并将其添加为新列数据框。
我试过
Z %>%
filter(d == 1) %>%
lm(y ~ t)
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误说"Error in as.data.frame.default(data) :
cannot coerce class ""formula"" to a data.frame"。但
lm(y ~ t, data = Z)
Run Code Online (Sandbox Code Playgroud)
工作正常。任何帮助,将不胜感激。
我们需要提取data和.代表数据对象
Z %>%
filter(d == 1) %>%
lm(y ~ t, data = .)
#Call:
#lm(formula = y ~ t, data = .)
#Coefficients:
#(Intercept) t
# 2 1
Run Code Online (Sandbox Code Playgroud)
在summarise/mutate/group_by和其他 tidyverse 函数中,我们可以简单地传递列名称。在这里,我们要么需要从数据环境中获取列,要么list在中创建输出summarise
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
Run Code Online (Sandbox Code Playgroud)