我想从由R中列定义的组组织的数据帧中生成长格式的计数表。我想要一些在熊猫中复制.groupby的东西。我确定dplyr可以做到,但是我找不到我想要的语法。
torch.nn.LSTM
我想创建类似这样的输出,并按“组”将每个国家或年份的计数分组:
# 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
感谢您的帮助。
答案 0 :(得分:3)
我们可以使用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