I have data of such structure:
data<-data.frame(TransactionNumber=rep(1:10, each=4),
Product=rep(c("a","b","c","d","e","f","g","c","i","j"), length.out=40))
TransactionNumber Product
1 1 a
2 1 b
3 1 c
4 1 d
5 2 e
6 2 f
7 2 g
8 2 c
9 3 i
10 3 j
11 3 a
12 3 b
13 4 c
14 4 d
15 4 e
16 4 f
17 5 g
18 5 c
19 5 i
20 5 j
21 6 a
22 6 b
23 6 c
24 6 d
25 7 e
26 7 f
27 7 g
28 7 c
29 8 i
30 8 j
31 8 a
32 8 b
33 9 c
34 9 d
35 9 e
36 9 f
37 10 g
38 10 c
39 10 i
40 10 j
I'm trying to get for each transaction numbers all possible combinations of two products present in given transaction (without repetitions). Each row would be one combination. So for transaction one I would get 1.ab 2. ac etc. I was unsuccessfully struggling with this for a while. Any ideas of simple solution? Thank you!
require(plyr)
ddply(data, "TransactionNumber", .fun=function(x) {
t(combn(as.character(x$Product), 2))
})
# TransactionNumber 1 2
# 1 1 a b
# 2 1 a c
# 3 1 a d
# 4 1 b c
# 5 1 b d
# 6 1 c d
# 7 2 e f
# 8 2 e g
# 9 2 e c
# 10 2 f g
# 11 2 f c
# 12 2 g c
# 13 3 i j
# ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.