在dplyr链中的group_by之后的{if ... else ..}语句

时间:2017-08-10 19:59:35

标签: r dplyr tidyverse

为了说明我尝试做的事情,我以钻石数据集为例。在group_by(cut)之后,我想在每个组上执行lm,具体取决于每个组的平均深度,然后将模型保存在数据框中。

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

花了一个小时来解决它但失败了。如果有人可以提供帮助,请欣赏它。

2 个答案:

答案 0 :(得分:2)

diamonds %>%
    group_by(cut) %>%
    do(model=if(mean(.$depth) > 60)
                lm(price ~ x, data=.)
             else lm(price ~ y, data=.))

答案 1 :(得分:1)

试试这个:

diamonds %>% group_by(cut) %>% 
  mutate(mean.depth=mean(depth),
         form = ifelse(mean.depth>60, 
                       "price~x", 
                       "price~y")) %>% 
  do(model = lm(as.formula(.$form), data = .))
Source: local data frame [5 x 2]
Groups: <by row>

# A tibble: 5 x 2

        cut    model
*     <ord>   <list>
1      Fair <S3: lm>
2      Good <S3: lm>
3 Very Good <S3: lm>
4   Premium <S3: lm>
5     Ideal <S3: lm>
相关问题