Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...