首页 > 解决方案 > 如何使用 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

示例图

谢谢您的帮助。

标签: rdataframedplyrgrouping

解决方案


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

推荐阅读