Reputation: 5546
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
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
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