The number of numerical combinations of events is displayed in the dataframe ext columns

This is an extension of the question asked in Count the number of times a combination of events occurs in the dataframe columns , I will ask the question again, so that's it here:

I have a data frame and I want to calculate the number of times each combination of events in two columns occurs (in any order), with zero if the combination does not appear.

For example, I have

df <- data.frame('x' = c('a', 'b', 'c', 'c', 'c'), 
                 'y' = c('c', 'c', 'a', 'a', 'b'))

So

x y  
a c  
b c  
c a  
c a  
c a  
c b

aand bdo not meet together, aand c4 times (lines 2, 4, 5, 6) band ctwice (3rd and 7th lines), so I would like to return

x-y num  
a-b 0  
a-c 4  
b-c 2  

Hope this makes sense? thanks in advance

0
3

, factor() expand.grid() ( )

all.possible <- expand.grid(c('a','b','c'), c('a','b','c'))
all.possible <- all.possible[all.possible[, 1] != all.possible[, 2], ]
all.possible <- unique(apply(all.possible, 1, function(x) paste(sort(x), collapse='-')))

df <- data.frame('x' = c('a', 'b', 'c', 'c', 'c'), 
                 'y' = c('c', 'c', 'a', 'a', 'b'))
table(factor(apply(df , 1, function(x) paste(sort(x), collapse='-')), levels=all.possible))
+1

:

res = table(df)

:

resdf = as.data.frame(res)

resdf data.frame :

  x y Freq
1 a a    0
2 b a    0
3 c a    2
4 a b    0
5 b b    0
6 c b    1
7 a c    1
8 b c    1
9 c c    0

, . , (a-c , c-a).

df1 = as.data.frame(t(apply(df,1,sort)))
+4

, . , ? , , , ...

df2 <- as.data.frame(table(df))
df2$com <- apply(df2[,1:2],1,function(x) if(x[1] != x[2]) paste(sort(x),collapse='-'))
df2 <- df2[df2$com != "NULL",]
ddply(df2, .(unlist(com)), summarise, 
      num = sum(Freq))
0

All Articles