首页 > 解决方案 > 查找组中事件的频率 dplyr

问题描述

我有一个分组的 df 具有不同长度的组。我想计算每个组中的 y/n 事件。因此,如果我有以下内容:

df <- data.frame(group = rep(1:4,times=c(20,10,17,8)),
                 outcome = rep(c("yes","yes","no","yes","no"),times = 11))

我想以一种我可以看到每个组中是的频率和否的频率的方式来总结这一点。就像是:

df %>% group_by(group) %>%
  summarise(freqyes = (. %>% filter(outcome=="yes") %>% n()) / n(),
            freqyes = (. %>% filter(outcome=="no") %>% n()) / n())

除了,那是行不通的。

每个组的是和否应该加到 100。

谢谢。

标签: rdplyrsummarize

解决方案


我们可以count然后计算比例group

library(dplyr)

df %>% count(group, outcome) %>% group_by(group) %>% mutate(n = n/sum(n) * 100)

#  group outcome   n
#  <int> <fct>   <dbl>
#1     1 no       40  
#2     1 yes      60  
#3     2 no       40  
#4     2 yes      60  
#5     3 no       35.3
#6     3 yes      64.7
#7     4 no       50  
#8     4 yes      50  

在基数 R 中,我们可以使用tableand prop.table

prop.table(table(df), 1) * 100

#    outcome
#group       no      yes
#    1 40.00000 60.00000
#    2 40.00000 60.00000
#    3 35.29412 64.70588
#    4 50.00000 50.00000

推荐阅读