Skip to content
Prev 200379 / 398503 Next

pairs

I stuck in another "7" in one of the lines with a 2 and reasoned that  
we could deal with the desire for non-ordered "pair counting" by  
pasting min(x,y) to max(x,y);

 > dput(prmtx)
structure(c(2, 1, 3, 9, 5, 7, 7, 8, 1, 7, 6, 5, 6, 2, 2, 7), .Dim =  
c(4L,
4L))
 > prmtx
      [,1] [,2] [,3] [,4]
[1,]    2    5    1    6
[2,]    1    7    7    2
[3,]    3    7    6    2
[4,]    9    8    5    7

 > pair.str <- sapply(1:nrow(prmtx), function(z)   
apply(combn(prmtx[z,], 2), 2,function(x) paste(min(x[2],x[1]),  
max(x[2],x[1]), sep=".")))

The logic:
sapply(1:nrow(prmtx), ... just loops over the rows of the matrix.
combn(prmtx[z,], 2)  ... returns a two row matrix of combination in a  
single row.
apply(combn(prmtx[z,], 2), 2 ... since combn( , 2)  returns a matrix  
that has two _rows_ I needed to loop over the columns.
paste(min(x[2],x[1]), max(x[2],x[1]), sep=".") ... stick the minimum  
of a pair in front of the max and separates them with a period to  
prevent two+ digits from being non-unique

Then using table() and logical tests in an index for the desired  
multiple pairs:


 > tpair <-table(pair.str)
 > tpair
pair.str
1.2 1.5 1.6 1.7 2.3 2.5 2.6 2.7 3.6 3.7 5.6 5.7 5.8 5.9 6.7 7.7 7.8  
7.9 8.9
   2   1   1   2   1   1   2   3   1   1   1   1   1   1   1   1   1    
1   1
 > tpair[tpair>1]
pair.str
1.2 1.7 2.6 2.7
   2   2   2   3