我有一个数据格式的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 2d是一个因子列。我知道,我想用lm来拟合一个线性模型,并将它作为一个新列添加到dataframe中,并将其添加到y over 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)效果很好。任何帮助都将不胜感激。
发布于 2018-03-21 09:36:09
我们需要提取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函数中,我们可以简单地传递列名。在这里,我们需要从数据环境中获取列,或者在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 https://stackoverflow.com/questions/49402641
复制相似问题