r - 如何使用 dplyr 以长格式按组创建计数
问题描述
我想从由 R 中的列定义的组组织的数据框中生成长格式的计数表。我想要在熊猫中复制 .groupby 的东西。我确信 dplyr 可以做到,但我找不到我想要的正确语法。
# Test data
Samples <- c('A01', 'A02', 'A03', 'A04', 'A05', 'A06', 'A07', 'A08', 'A09', 'A10', 'A11', 'A12', 'A13', 'A14', 'A15', 'A16', 'A17', 'A18', 'A19', 'A20')
Group <- c(1, 1, 3, 2, 1, 3, 2, 2, 1, 1, 1, 2, 2, 1, 3, 1, 1, 3, 1, 2)
Country <- c('Thailand', 'Vietnam', 'Cambodia', 'Vietnam', 'Cambodia', 'Thailand', 'Laos', 'Vietnam', 'Vietnam', 'Vietnam', 'Laos', 'Cambodia', 'Vietnam', 'Cambodia', 'Cambodia', 'Laos', 'Laos', 'Cambodia', 'Cambodia', 'Vietnam')
Year <- c(2012, 2018, 2012, 2018, 2018, 2012, 2018, 2018, 2018, 2012, 2018, 2018, 2018, 2012, 2012, 2018, 2018, 2012, 2018, 2012)
df = data.frame(Samples, Group, Country, Year, row.names=c(1))
df
我想创建这样的输出,按“组”分组,每个国家或年份的计数:
# Desired output 1 - country counts
Group_name <- c(1, 1, 1, 1, 2, 2, 2, 3, 3)
Countries_bygroup <- c('Cambodia', 'Laos', 'Thailand', 'Vietnam', 'Cambodia', 'Laos', 'Vietnam', 'Cambodia', 'Thailand')
Country_counts <- c(3, 3, 1, 3, 1, 1, 4, 3, 1)
group_by_country = data.frame(Group_name, Countries_bygroup, Country_counts)
group_by_country
# Desired output 2 - Year counts
Group_name2 <- c(1, 1, 2, 2, 3)
Years_bygroup <- c(2012, 2018, 2012, 2018, 2012)
Year_counts <- c(3, 7, 1, 5, 4)
group_by_year = data.frame(Group_name2, Years_bygroup, Year_counts)
group_by_year
最终结果是我想制作这样的图:
# Plot by country
library('ggplot2')
plot <- ggplot(group_by_country, aes(x = Group_name, y = Country_counts, fill = Countries_bygroup)) +
geom_bar(position = "fill",stat = "identity") +
scale_y_continuous(labels = percent_format()) +
xlab("Sample group") +
ylab("")
plot
谢谢您的帮助。
解决方案
我们可以count
使用dplyr
. 不需要group_by
列,因为该count
功能可以自动处理分组。只需将要计算的列放入函数中即可。
library(dplyr)
df %>% count(Group, Country)
# # A tibble: 9 x 3
# Group Country n
# <dbl> <fct> <int>
# 1 1 Cambodia 3
# 2 1 Laos 3
# 3 1 Thailand 1
# 4 1 Vietnam 3
# 5 2 Cambodia 1
# 6 2 Laos 1
# 7 2 Vietnam 4
# 8 3 Cambodia 3
# 9 3 Thailand 1
df %>% count(Group, Year)
# # A tibble: 5 x 3
# Group Year n
# <dbl> <dbl> <int>
# 1 1 2012 3
# 2 1 2018 7
# 3 2 2012 1
# 4 2 2018 5
# 5 3 2012 4
推荐阅读
- authentication - StackOverflow 团队使用 ADFS SSO 的身份验证方法、角色分配
- sql - 如何从 JSONB、VARCHAR 和 DATE 类型的列创建 Postgresql 生成的 JSONB 类型列
- azure-devops - 如何下载运行管道对话框中指定的工件?
- swift - 在闭包内捕获闭包:Xcode 抛出错误:转义闭包捕获非转义参数
- python - 尝试将 2 code.assign() 添加到 CloudFormation 部署操作的 parameter_overrides 时出错
- node.js - 如何处理 Firebase Cloud Functions 无限循环?
- javascript - API 评论问题
- expo - 如何使用 Expo Application Services (EAS) 构建和发布 expo 应用程序
- python - Django:使用 DATE_FORMAT 将 DateField 转换为字符串
- c++ - C++:url 阅读器功能不适用于带有 \ 符号的 URL 链接。请帮助我