将`%>%`与`lm`和`rbind`一起使用 [英] Using `%>%` with `lm` and `rbind`

查看:95
本文介绍了将`%>%`与`lm`和`rbind`一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe Z looking like

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中的两个因子拟合一个线性模型,其中lmyt上,并将其作为新列添加到数据框中.

with d being a factor column. I know want to fit a linear model with lm to y over t for both factors in d and add it as a new column to the dataframe.

我尝试过

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

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

but this gives me an error saying "Error in as.data.frame.default(data) : cannot coerce class ""formula"" to a data.frame". But

lm(y ~ t, data = Z)

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

works fine. Any help would be appreciated.

推荐答案

我们需要提取data,而.代表数据对象

We need to extract the data and . represents the data object

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


Within the summarise/mutate/group_by and other tidyverse functions, we can simply pass the column name. Here, either we need to get the columns from within the environment of data or create a list output in 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  

这篇关于将`%>%`与`lm`和`rbind`一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆