R is a sequence of continuous cases, where end1 == start2

Take this dataset ...

test <- data.frame(
    t1=c(2,3,5,6,7,10,10),
    t2=c(3,4,6,7,8,11,12),
    id=1:7
)

... which looks like this. To clarify, each row is a previously identified association of two cases that must remain connected together.

  t1 t2 id
1  2  3  1
2  3  4  2
3  5  6  3
4  6  7  4
5  7  8  5
6 10 11  6
7 10 12  7

I hope to identify continuous sequences based on t2 == t1 recursively, so the links are:

link1 -  2-3,3-4
link2 -  5-6,6-7,7-8
link3 -  10-11
link4 -  10-12

The end result I'm looking for is:

  t1 t2 id matchid
1  2  3  1       1
2  3  4  2       1
3  5  6  3       2
4  6  7  4       2
5  7  8  5       2
6 10 11  6       3
7 10 12  7       4

I experimented with match(test$t2,test$t1)to get the source links, but now I'm stuck on how to continue the linking process. My thoughts keep returning to using the loop, and it sounds like a terrible way to go.

+3
source share
1 answer

Here is one way to do this:

test$matchid <- c(1, 1 + cumsum(tail(test$t1, -1) != head(test$t2, -1)))
+6
source

All Articles