[R] Selecting transitive couples

Duncan Murdoch murdoch at stats.uwo.ca
Tue Nov 13 19:33:49 CET 2001


On Tue, 13 Nov 2001 17:55:10 +0100 (MET), you wrote in message
<Pine.OSF.3.96.1011113175336.18472K-100000 at ija.csic.es>:

>My goal is to select the transitive pairs, i.e., in
>the above example:
>
>2 5 (because there is 5 2 as well)
>6 8 (because there is 8 6 as well)
>
>The task is simple with a for loop, but
>can anybody suggest a "genuine R" solution?
>(That is, a vectorised operation).

This isn't as fast as it could be (it sorts the data twice), and might
not give the results in the format you like, but it should provide a
starting point:

transitive <- function(pairs)
{  both <- rbind(cbind(0,pairs), 
                 cbind(1,pairs[,2],pairs[,1]))
   both <- paste(both[,1],both[,2],both[,3])
   both <- unique(both)
   both <- substring(both,first=3)
   both[duplicated(both)]
}

It works by sticking together the original data with a transposed
copy, then looking for duplicates. ( The 0's and 1's, the unique()
call in the middle, and the substring extraction are only necessary if
you haven't already assured that each pair is unique.)  It works with
strings, so if you've got real values that might be displayed
identically even when not identical, it won't work.

Duncan Murdoch
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list