如何获得每个类别的计数

时间:2019-11-06 19:36:57

标签: r dataframe

我想获取R Studio中每个类别的计数摘要。 这是一个可重现的示例:

column_1 <- c("A","A","A","A","B","B","C","C","C","C","C","D","D","D")
column_2 <- c("YES","NO","YES","YES","YES","NO","YES","YES","YES","NO","YES","YES","YES","NO")
df <- data.frame(column_1,column_2)

我希望结果是这样的:计算每个类别A B C D的“是”和“否”的数量。请参见下图:

enter image description here

2 个答案:

答案 0 :(得分:3)

在这里:

library(tidyverse)

column_1 <- c("A","A","A","A","B","B","C","C","C","C","C","D","D","D")
column_2 <- c("YES","NO","YES","YES","YES","NO","YES","YES","YES","NO","YES","YES","YES","NO")
df <- data.frame(column_1,column_2)

df %>% group_by(column_1) %>%count(column_2) %>% spread(column_2, n)

我很难记住传播功能,该功能有助于从长数据到宽数据。该网站非常有帮助:http://www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/

答案 1 :(得分:1)

我们可以使用dcast

library(reshape2)
dcast(df, column_1 ~ paste0(column_2, "_count"), length)