How to identify multiple identical pairs in two vectors

Posted by Sacha Epskamp on Stack Overflow See other posts from Stack Overflow or by Sacha Epskamp
Published on 2011-02-15T21:20:57Z Indexed on 2011/02/15 23:25 UTC
Read the original article Hit count: 160

Filed under:

In my graph-package (as in graph theory, nodes connected by edges) I have a vector indicating for each edge the node of origin from, a vector indicating for each edge the node of destination to and a vector indicating the curve of each edge curve.

By default I want edges to have a curve of 0 if there is only one edge between two nodes and curve of 0.2 if there are two edges between two nodes. The code that I use now is a for-loop, and it is kinda slow:

curve <- rep(0,5)
from<-c(1,2,3,3,2)
to<-c(2,3,4,2,1)

    for (i in 1:length(from))
    {
        if (any(from==to[i] & to==from[i]))
        {
            curve[i]=0.2        

        }
    }

So basically I look for each edge (one index in from and one in to) if there is any other pair in from and to that use the same nodes (numbers).

What I am looking for are two things:

  1. A way to identify if there is any pair of nodes that have two edges between them (so I can omit the loop if not)
  2. A way to speed up this loop

#

EDIT:

To make this abit clearer, another example:

from <- c(4L, 6L, 7L, 8L, 1L, 9L, 5L, 1L, 2L, 1L, 10L, 2L, 6L, 7L, 10L, 4L, 9L)
to <- c(1L, 1L, 1L, 2L, 3L, 3L, 4L, 5L, 6L, 7L, 7L, 8L, 8L, 8L, 8L, 10L, 10L)
cbind(from,to)
      from to
 [1,]    4  1
 [2,]    6  1
 [3,]    7  1
 [4,]    8  2
 [5,]    1  3
 [6,]    9  3
 [7,]    5  4
 [8,]    1  5
 [9,]    2  6
[10,]    1  7
[11,]   10  7
[12,]    2  8
[13,]    6  8
[14,]    7  8
[15,]   10  8
[16,]    4 10
[17,]    9 10

In these two vectors, pair 3 is identical to pair 10 (both 1 and 7 in different orders) and pairs 4 and 12 are identical (both 2 and 8). So I would want curve to become:

 [1,]  0.0
 [2,]  0.0
 [3,]  0.2
 [4,]  0.2
 [5,]  0.0
 [6,]  0.0
 [7,]  0.0
 [8,]  0.0
 [9,]  0.0
[10,]  0.2
[11,]  0.0
[12,]  0.2
[13,]  0.0
[14,]  0.0
[15,]  0.0
[16,]  0.0
[17,]  0.0

(as I vector, I transposed twice to get row numbers).

© Stack Overflow or respective owner

Related posts about r