2

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?

Minyi Han
  • 691
  • 5
  • 14

1 Answers1

5

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))
akrun
  • 789,025
  • 32
  • 460
  • 575