5

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
ADJ
  • 4,892
  • 10
  • 50
  • 83
  • 1
    bit of a hack but works : `tt <- tcrossprod(df$b,1/df$b); tt[upper.tri(tt) ] <- NA; reshape2::melt(tt, na.rm=T);` – user20650 Jan 27 '15 at 23:27
  • @user20650 I think the first occurrences in the table correspond to the lower triangular portion, should use `lower.tri` rather than `upper.tri`, and should additionally use the argument `diag = TRUE` since we want those diagonal elements as well. – tkmckenzie Jan 27 '15 at 23:29
  • hi @tkmckenzie; try the code - i think it produces the right order and we dont want `diag=TRUE` as this will set the diagonal entries to `NA` – user20650 Jan 27 '15 at 23:35
  • @user20650 My mistake, my mind was on a different track and I read your code too quickly, you're exactly right. – tkmckenzie Jan 28 '15 at 00:09

1 Answers1

4

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
Marat Talipov
  • 13,064
  • 5
  • 34
  • 53
  • Should probably be `subset(m, X1 >= X2)` – Josh O'Brien Jan 27 '15 at 23:54
  • Sure, it could be X1 >= X2 if needed to account for diagonal elements. I didn't do that because OP didn't say anything about them, and I assumed from his previous question on this topic (http://stackoverflow.com/q/28158426/1898580) that diagonal elements are of no interest here. – Marat Talipov Jan 27 '15 at 23:57
  • 1
    Aha, didn't know there were other related questions, so I was just going off of the phrase "first occurrence of a combination". – Josh O'Brien Jan 28 '15 at 00:05