R - sequence of continuous cases where end1 == start2
dataframe, match, r, sequence
Solution
Here is one way to do it:
test$matchid <- c(1, 1 + cumsum(tail(test$t1, -1) != head(test$t2, -1)))
Problem
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 link of two cases that have to stay bound 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 am hoping to identify the continuous sequences based on t2 == t1 recursively so that 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 this: ``` 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 have experimented with `match(test$t2,test$t1)` to get the initial links but am now getting stuck on how to continue the linking process. My thoughts keep falling back to using a loop and that sounds like a terrible way to go.