Search code examples
rcalculus

How to substract a column by row?


I want to do an easy subtract in R, but I don't know how to solve it. I would like to know if I have to do a loop or if there is a function.

I have a column with numeric variables, and I would like to subtract n by n-1.

Time_Day Diff
10  10
15  5
45  30
60  15

Thus, I would like to find the variable "Diff".


Solution

  • you can also try with package dplyr

    library(dplyr)
    mutate(df, dif=Time_Day-lag(Time_Day))
    #   Time_Day Diff dif
    # 1       10   10  NA
    # 2       15    5   5
    # 3       45   30  30
    # 4       60   15  15