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

狂风中的少年 提交于 2019-12-11 07:07:46

问题


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=.))}

This is what I got:

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.


回答1:


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



回答2:


Try this:

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>


来源:https://stackoverflow.com/questions/45622540/if-else-statement-after-group-by-in-dplyr-chain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!