Use diff
with transform
:
dat <- read.table(text="xy 5 3 8 9 3 1 1 5", header=T) transform(dat, dx=c(NA, diff(x)), dy=c(NA, diff(y)))
Yielding:
xy dx dy 1 5 3 NA NA 2 8 9 3 6 3 3 1 -5 -8 4 1 5 -2 4
And like og dplyr :
library(dplyr) dat %>% mutate(dx=c(NA, diff(x)), dy=c(NA, diff(y)))
source share