【问题标题】:find frequency of events in groups dplyr查找组中事件的频率 dplyr
【发布时间】:2020-06-12 03:44:14
【问题描述】:

我有一个具有不同长度组的分组 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。

谢谢。

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:

    我们可以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  
    

    在base R中,我们可以使用tableprop.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多