Ashish Ashish - 1 year ago 94
R Question

Get the difference between two non consecutive rows

I am new to R and stuck in getting the difference between two non consecutive rows. My Data frame looks like:

Column 1 | Column 2
Row1 1 | 5
Row2 3 | 6
Row3 8 | 10
Row4 6 | 1
Row5 28 | 5
Row6 7 | 4


I need to find the difference between Row1 and Row4, Row2 and Row5, Row3 and Row6 and so on. I have done this using For loop by giving the intervals but, its taking lots of time as there are huge number of rows.

Is there any other way to do it?

Answer Source

This should do the trick. However the last few rows are omitted from the output so the matrix obtained is smaller than your input.

diff(as.matrix(your_data_frame), lag = 3)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download