Noah Watkins
Noah Watkins

Reputation: 5546

Subtract shifted vectors in R

Say I have a vector in R:

x <- c(1,2,3)

is there a concise way to create a new vector y that is one less than the size of x where:

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

without using a for-loop?

Upvotes: 8

Views: 6488

Answers (2)

Henry
Henry

Reputation: 6784

diff(x)is the obvious answer.

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

Upvotes: 14

Gong-Yi Liao
Gong-Yi Liao

Reputation: 609

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

example :

diff(x)

may help you.

Upvotes: 5

Related Questions