Counting unique pairs of categorical variables in R [duplicate]

假如想象 提交于 2019-12-10 13:47:43

问题


If I have this data:

One <- c(rep("X",4),rep("Y",3),rep("Z",2))
Two <- c(rep("A",2),rep("B",6),rep("C",1))

df <- data.frame(One,Two) 

  One Two
1   X   A
2   X   A
3   X   B
4   X   B
5   Y   B
6   Y   B
7   Y   B
8   Z   B
9   Z   C

I want to find the frequency of unique pairs (one,two). I know if I wanted to find the frequency of different elements in column One I would do table(df$one). How about the frequency of unique pairs?


回答1:


table(as.character(interaction(df)))

Or

library(qdap)
table(paste2(df))

# X.A X.B Y.B Z.B Z.C 
#   2   2   3   1   1 



回答2:


This is the dplyr solution.

library(dplyr)

df %>% group_by(One,Two) %>%
      summarize(Count = n())

This returns a data frame like this

Source: local data frame [5 x 3]
Groups: One

  One Two Count
1   X   A     2
2   X   B     2
3   Y   B     3
4   Z   B     1
5   Z   C     1


来源:https://stackoverflow.com/questions/24925306/counting-unique-pairs-of-categorical-variables-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!