for example
a <- c(7, 10, 5, 4, 11)
and I would like to b as:
b[1] = 0,
b[2] = a[2] - a[1],
b[3] = a[3] - a[2],
b[4] = a[4] - a[3],
b[5] = a[5] - a[4]
is there a function to obtain these values automatically?
We can use diff
b <- c(0, diff(a))
Or another option is lag
from dplyr
library(dplyr)
b <- a - lag(a, default = first(a))