r - 如何使用 dplyr 按组以长格式创建计数

标签 r dataframe dplyr grouping

我想从由 R 中的列定义的组组织的数据帧生成长格式的计数表。我想要一些在 Pandas 中复制 .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

Example 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

关于r - 如何使用 dplyr 按组以长格式创建计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55305380/

相关文章:

使用 dplyr rename(across(

r - 当 x 轴是分类的时,如何标记水平线?

r - 根据列中每个元素的条件计算出现次数

r - 如何根据 R 中的条件用字符串替换 NA?

r - 从每一行获取索引并与原始 data.frame 合并

r - R的替代命令中的取消引号字符串

r - MICE 中的“主要次要 % 不是正定”错误

python - 向具有不同行数的 Pandas 数据框添加新列

r - 基于每组行数的子集数据帧

r - 根据字符串中多个单词的精确匹配转换新列