Search code examples
rmeltcross-product

R tcrossprod with unique combinations


There might be a version of tcrossprod that achieves this but I wasn't able to find it. From the example below, how to I get only rows with the first occurrence of a combination, if order doesn't matter? I.e. (1,2) for me is the same as (2,1).

a <- c(1,2,3,4)
b <- c(10,5,4,10)
df<- data.frame(a,b)

melt(tcrossprod(df$b,1/df$b))

> melt(tcrossprod(df$b,1/df$b))
   Var1 Var2 value
1     1    1  1.00
2     2    1  0.50
3     3    1  0.40
4     4    1  1.00
5     1    2  2.00
6     2    2  1.00
7     3    2  0.80
8     4    2  2.00
9     1    3  2.50
10    2    3  1.25
11    3    3  1.00
12    4    3  2.50
13    1    4  1.00
14    2    4  0.50
15    3    4  0.40
16    4    4  1.00

Solution

  • Having m <- melt(tcrossprod(df$b,1/df$b)), you can simply do:

    subset(m,X1>X2)
    
    #   X1 X2 value
    #2   2  1   0.5
    #3   3  1   0.4
    #4   4  1   1.0
    #7   3  2   0.8
    #8   4  2   2.0
    #12  4  3   2.5