Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between neighbouring elements of a vector

Tags:

loops

r

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.

like image 531
user3296555 Avatar asked Feb 11 '14 09:02

user3296555


2 Answers

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

like image 93
bartektartanus Avatar answered Sep 19 '22 16:09

bartektartanus


x <- c(1,3,3,9) 
(z <- x[-1] - head(x, -1))
# [1] 2 0 6
like image 24
lukeA Avatar answered Sep 21 '22 16:09

lukeA