7

I have a dataframe like so:

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

start end
    5   2
    4   6
    2   3

And I want the following result:

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

Essentially it is:

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

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

What is a good way of doing this in R?

Frank
  • 66,179
  • 8
  • 96
  • 180
SonicProtein
  • 840
  • 1
  • 11
  • 28

2 Answers2

13

Just 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
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Missing closing parenthesis at end of df$diff statement. Statement should read: df$diff <- c(NA,df[2:nrow(df), 2] - df[1:(nrow(df)-1), 1]) – makeyourownmaker Mar 03 '17 at 10:27
2
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
user227710
  • 3,164
  • 18
  • 35