使用dplyr计算按组和逻辑值的平均值之间的差异

时间:2017-12-09 15:38:53

标签: r dplyr summarize

是否有人知道如何使用dplyr计算some_var == TRUEsome_var == FALSE的平均值之间的差异,并按第三个变量进行分组?

例如,给出以下示例数据帧:

library('dplyr')

dat <- iris %>% 
     mutate(wide=Sepal.Width > 3) %>% 
     group_by(Species, wide) %>% 
     summarize(mean_width=mean(Sepal.Width))

dat

# A tibble: 6 x 3
# Groups:   Species [?]
     Species  wide mean_width
      <fctr> <lgl>      <dbl>
1     setosa FALSE   2.900000
2     setosa  TRUE   3.528571
3 versicolor FALSE   2.688095
4 versicolor  TRUE   3.200000
5  virginica FALSE   2.800000
6  virginica  TRUE   3.311765

是否有人知道如何根据物种推导出wide == TRUEwide == FALSE的差异的新数据框?

可以使用以下几种语句来完成:

false_vals <- dat %>% filter(wide==FALSE)
true_vals <- dat %>% filter(wide==TRUE)

diff <- data.frame(Species=unique(dat$Species), diff=true_vals$mean_width - false_vals$mean_width)

> diff
     Species      diff
1     setosa 0.6285714
2 versicolor 0.5119048
3  virginica 0.5117647

但是,这似乎应该可以直接使用dplyr实现。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

使用spread()包中的tidyr

library(tidyr)

iris %>% mutate(wide=Sepal.Width > 3) %>% 
        group_by(Species, wide) %>% 
        summarize(mean_width=mean(Sepal.Width)) %>%
        spread(wide, mean_width) %>%
        summarise(diff = `TRUE` - `FALSE`)
#     Species      diff
#1     setosa 0.6285714
#2 versicolor 0.5119048
#3  virginica 0.5117647

答案 1 :(得分:1)

对于新版本的Tidyr软件包(> 1.0.0),现在最好使用 pivot_wider 命令而不是 spread 。其更直观,更扩展的命令将来可能会弃用。

library(tidyr)

    iris %>% mutate(wide=Sepal.Width > 3) %>% 
            group_by(Species, wide) %>% 
            summarize(mean_width=mean(Sepal.Width)) %>%
            pivot_wider(names_from = wide, values_from = mean_width) %>%
            summarise(diff = `TRUE` - `FALSE`)

    #     Species      diff
    #1     setosa 0.6285714
    #2 versicolor 0.5119048
    #3  virginica 0.5117647