dplyr链中group_by之后的{if ... else ..}语句 [英] {if...else..} statement after group_by in dplyr chain
本文介绍了dplyr链中group_by之后的{if ... else ..}语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了说明我要执行的操作,我以Diamond数据集为例。在group_by(cut)之后,我想根据每个组的平均深度在每个组上执行lm,然后将模型保存在数据框中。
To illustrate what I'm trying to do, I'm using diamond dataset as an example. After group_by(cut), I want to do lm on each group, depending on the mean depth of each group, and then save the model in the dataframe.
diamonds %>% group_by(cut) %>%
mutate(mean.depth=mean(depth)) %>%
{if (.$mean.depth>60) do(model=lm(price~x, data=.))
else do(model=lm(price~y, data=.))}
这就是我得到的:
Error in function_list[[k]](value) : object 'mean.depth' not found
小时修复它,但失败了。
Spent an hour to fix it but failed. Appreciate it if anyone can help.
推荐答案
diamonds %>%
group_by(cut) %>%
do(model=if(mean(.$depth) > 60)
lm(price ~ x, data=.)
else lm(price ~ y, data=.))
这篇关于dplyr链中group_by之后的{if ... else ..}语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文