r - 查找组中事件的频率 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。
谢谢。
解决方案
我们可以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 中,我们可以使用table
and 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
推荐阅读
- html - CSS 在网格中定位粘性侧边栏
- .net-core - 为生产禁用控制器 API 端点
- javascript - 设置最大边界不起作用传单
- c# - WPF C#:我的文本编辑器应该是文本文件的默认程序吗?
- c# - 如何在c#中确认进程关闭
- asp.net-mvc - 使用插件更改样式后,jquery 不再填充 MVC 5 选择下拉列表
- haskell - 在 Haskell 中查找给定树中的最大分支
- vuetify.js - 更改 vuetify UI 组件的基本语言
- amazon-dynamodb - CSV/parquet 到 Dynamo,约 50 万行的小文件,只有两列
- xcode - 调用 beginSheet:completionHandler 后如何等待工作表完成: