2017-08-10 59 views
1

为了说明我正在尝试执行的操作,我以钻石数据集为例。在group_by(cut)之后,我想对每个组做lm,具体取决于每个组的平均深度,然后将模型保存在数据框中。{if ... else ..}在dplyr链中的group_by之后的语句

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

我把'if'内'做()'(可能是在一个匿名函数) – Gregor

+0

怎么办' (model = lm(if(mean(。$ depth)> 60){price〜x} else {price〜y},data =。)'。只是如果公式 –

回答

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