ShrestR
ShrestR

Reputation: 293

R getting difference

I am trying to use R to return some value, such as if the difference between two rows (i+1) and i is less than or equal to 1 then "node"=1. My data look like:

   id   x        y
   1    7        1
   2    7        2
   3    7        2
   4    7        4
   5    7        5
   6    7        7
   7    7        8
   8    7        10
   9    7        10
  10    7        12

I want to get:

   id   x        y  diff  node
   1    7        1  0     1
   2    7        2  1     1
   3    7        2  1     1
   4    7        4  2     2
   5    7        5  1     2
   6    7        7  2     3
   7    7        8  1     3
   8    7        10 2     4
   9    7        10 0     4
  10    7        12 2     5

Above, diff is difference between two successive rows, including the difference of 1st row and 1st row = 0 . And node is 1 for the first difference if diff <=1, otherwise 2 until diff<=1. If diff>1 then node=3, and so on.

I have tried to explain as clearly as possible, I apologize if I am not clear enough.

Upvotes: 0

Views: 73

Answers (1)

thelatemail
thelatemail

Reputation: 93938

Try this, assuming your data.frame is called dat:

dat$node <- c(0,cumsum(diff(dat$y)>1))+1
dat$diff <- c(0,ifelse(diff(dat$y)>1,2,1))

Giving:

> dat
   id x  y node diff
1   1 7  1    1    0
2   2 7  2    1    1
3   3 7  2    1    1
4   4 7  4    2    2
5   5 7  5    2    1
6   6 7  7    3    2
7   7 7  8    3    1
8   8 7 10    4    2
9   9 7 10    4    1
10 10 7 12    5    2

Upvotes: 2

Related Questions