user3296555
user3296555

Reputation: 151

Difference between neighbouring elements of a vector

I have no idea how to solve an introductory exercise to R, so the exercise is

Create a vector z with all 99 differences between the neighbouring elements of x such that z[1]=x[2]-x[1], z[2]=x[3]-x[2], . . .

I guess it is supposed to work without loops.

Upvotes: 14

Views: 15230

Answers (2)

bartektartanus
bartektartanus

Reputation: 16080

Sounds like diff function

diff(x)

You can also use this code:

x[-1] - x[-length(x)]

x[-1] - vector x without first element

x[-length(x)] - vector x without last element

Upvotes: 30

lukeA
lukeA

Reputation: 54237

x <- c(1,3,3,9) 
(z <- x[-1] - head(x, -1))
# [1] 2 0 6

Upvotes: 6

Related Questions