Wimpel Wimpel - 1 year ago 71
R Question

R: merge rows, based on column value and value different column in next row

I've got a dataframe with two columns: "From" and "To"

From To
a b
b c
c d
e f

What I would like to achieve, is to check is 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 tyhe next "To". Also, the next row can be deleted.

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

The endresult would look lie 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
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download