Subtract shifted vectors in R

Say I have a vector in R:

x <- c(1,2,3) 

There is a simplified way to create a new vector y, which is smaller than the size x, where:

 y <- x[i+1] - x[i] 

without using a for loop?

+6
source share
2 answers

diff(x) is the obvious answer.

A simpler alternative is x[-1] - x[-length(x)] , and this can easily be adapted, for example, to sums or products of consecutive terms

+11
source

You can use "diff" to get the difference between two consecutive items in a list,

example:

 diff(x) 

can help you.

+2
source

Source: https://habr.com/ru/post/909225/


All Articles