Transforming a two-way table() into pairwise list of counts in R

这一生的挚爱 提交于 2019-12-24 23:25:22

问题


Starting with some sample two-way frequency table:

a <- c(1,2,3,4,4,3,4,2,2,2)
b <- c(1,2,3,4,1,2,4,3,2,2)

tab <- table(a,b)
> tab
   b
a   1 2 3 4
  1 1 0 0 0
  2 0 3 1 0
  3 0 1 1 0
  4 1 0 0 2

I need to transform the table into the following format:

goal <- data.frame(a=c(1,2,3,4),b=c(1,2,3,4),count=c(1,3,1,2))
    > goal
  a b count
1 1 1     1
2 2 2     3
3 3 3     1
4 4 4     2
. . .     .

How can I form all pairwise combinations from the two-way table and add the frequency counts in the third column?

Intuition tells me there should be a simple kind of 'reverse' function for table, but I could not find anything on SO or Google.


回答1:


Naturally, after posting the question I found the right search query for Google...

> as.data.frame(tab)
   a b Freq
1  1 1    1
2  2 1    0
3  3 1    0
4  4 1    1
5  1 2    0
6  2 2    3
7  3 2    1
8  4 2    0
9  1 3    0
10 2 3    1
11 3 3    1
12 4 3    0
13 1 4    0
14 2 4    0
15 3 4    0
16 4 4    2


来源:https://stackoverflow.com/questions/24009934/transforming-a-two-way-table-into-pairwise-list-of-counts-in-r

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