1
votes

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?

1
Use diff function with lag argument. - user2100721
What happens after row 6? Is row 7 compared with row 10? - Jaap
What should be done with your last rows (the ones which do not have a corresponding +3 row in your data)? - LAP
@user2100721 - thanks for your reply. I tried diff function buy its giving me error as Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : non-numeric argument to binary operator. - Ashish
@Jaap - yes after row 6, row 7 compares with row 7 and this goes till row ~40000. - Ashish

1 Answers

0
votes

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)