查找组dplyr中的事件频率
我有一个不同长度的分组df。我想统计每个组中的y/n事件。因此,如果我有以下几点:查找组dplyr中的事件频率,r,dplyr,summarize,R,Dplyr,Summarize,我有一个不同长度的分组df。我想统计每个组中的y/n事件。因此,如果我有以下几点: df我们可以计数,然后按组计算比例 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
df我们可以计数
,然后按组
计算比例
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
我们可以计数
,然后按分组
计算比例
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
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