R how can I calculate difference between rows in a data frame

前端 未结 6 2049
挽巷
挽巷 2020-12-03 01:13

Here is a simple example of my problem:

> df <- data.frame(ID=1:10,Score=4*10:1)
> df
       ID Score
    1   1    40
    2   2    36
    3   3    3         


        
6条回答
  •  温柔的废话
    2020-12-03 01:35

    Perhaps you are looking for something like this:

    > tail(df, -1) - head(df, -1)
       ID Score
    2   1    -4
    3   1    -4
    4   1    -4
    5   1    -4
    6   1    -4
    7   1    -4
    8   1    -4
    9   1    -4
    10  1    -4
    

    You can subtract or add two data.frames together if they are the same dimensions. So, what we are doing here is subtracting one data.frame that is missing the first row (tail(df, -1)) and one that is missing the last row (head(df, -1)) and subtracting them.

提交回复
热议问题