The difference between adjacent elements of the vector in R

I'm sorry to bother you, but I have no idea how to solve R.'s introductory exercise (Of course, I did really ambitiously before posting!). Thus, exercise "Create a vector z with all 99 differences between neighboring elements x for which z [1] = x [2] -x [1], z [2] = x [3] -x [2] ,. , "I guess it should work without loops. I guess this is pretty simple, but I'm completely new to R.

thanks for the help

+3
source share
2 answers

Sounds like a 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)] is the vector x without the last element

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

All Articles