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

{if...else..} statement after group_by in dplyr chain

为了说明我正在尝试做的事情,我以钻石数据集为例。在 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

花了一个小时修复它但失败了。如果有人能提供帮助,将不胜感激。

试试这个:

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>
diamonds %>%
    group_by(cut) %>%
    do(model=if(mean(.$depth) > 60)
                lm(price ~ x, data=.)
             else lm(price ~ y, data=.))