Subtract R from the previous row

I have a data beat:

df <- data.frame(start=c(5,4,2),end=c(2,6,3))

start end
    5   2
    4   6
    2   3

And I want to get the following result:

start end diff
    5   2 
    4   6    1
    2   3   -1

Essentially this:

end[2] (second row) - start[1] = 6-5=1

and end[3] - start[2] = 3-4 = -1

What is a good way to do this in R?

+4
source share
2 answers

A simple vector subtraction should work

df$diff <- c(NA,df[2:nrow(df), 2] - df[1:(nrow(df)-1), 1])

  start end diff
1     5   2   NA
2     4   6    1
3     2   3   -1
+10
source
library(data.table)

setDT(df)[,value:=end-shift(start,1,type="lag")]
   start end value
1:     5   2    NA
2:     4   6     1
3:     2   3    -1
+2
source

All Articles