Subtract from the previous row R [duplicate]

南笙酒味 提交于 2019-12-05 00:11:21

问题


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?


回答1:


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



回答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


来源:https://stackoverflow.com/questions/30448709/subtract-from-the-previous-row-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!