Wimpel Wimpel - 7 months ago 24
R Question

Merge rows based on column value and value different column in next row

I have a data frame with two columns: "From" and "To"

From To
a b
b c
c d
e f

I would like to check if the "From" on the next row is the same as the "To" in the current row. If so, then the "To" in the current row can be substituted with the next "To". Also, the next row can be deleted.

This has to continue/loop until no row has a "To" which is the same as the next line's "From".

The end result would look like this:

From To
a d
e f

I'm stuck here... Can't figure out how to pass/delete the rows so that the endresult is achieved...

lmo lmo

This code works for your example.

data.frame("From"=df$From[c(TRUE, head(df$To, -1) != tail(df$From, -1))], 
           "To"=df$To[c(head(df$To, -1) != tail(df$From, -1), TRUE)])
  From To
1    a  d
2    e  f

It works by offsetting the order of the From and To vectors, to include the first From element and the last To element, and compare subsequent From elements with the preceding To element.