0

I tried to find all possible combinations by group. I tried to use combn function and data.table package as a below post teaches [(here is the link)](Generate All ID Pairs, by group with data.table in R

This gives me the expected result.

dat1 <- data.table(ids=1:4, groups=c("B","A","B","A"))
dat1
   ids groups
1:   1      B
2:   2      A
3:   3      B
4:   4      A

dat1[, as.data.table(t(combn(ids, 2))), .(groups)]
   groups V1 V2
1:      B  1  3
2:      A  2  4

But this gives me a strange result. It's very weird. I tried to understand this result for about 3 hours but I can't. Isn't it a bug?

dat2 <- data.table(ids=1:4, groups=c("B","A","B","C"))
dat2
   ids groups
1:   1      B
2:   2      A
3:   3      B
4:   4      C

dat2[, as.data.table(t(combn(ids, 2))), .(    groups)]
   groups V1 V2
1:      B  1  3
2:      A  1  2
3:      C  1  2
4:      C  1  3
5:      C  1  4
6:      C  2  3
7:      C  2  4
8:      C  3  4

I really appreciate it for your teaching.

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
aasungh
  • 85
  • 1
  • 5
  • 1
    The behavior appears correct. If you look at the documentation for `combn(x, m)`, when `x` is an integer instead of a vector, it is evaluated as `seq_len(x)`. In your example, both A & C are integers 2 and 4 respectively, so they are evaluated as 2-number combinations of 1:2 and 1:4, respectively. – oshun Jan 14 '17 at 18:25
  • @oshun Wow Thank you so much! – aasungh Jan 14 '17 at 18:34

0 Answers0