arrays - Process pairs of elements in a vector -


is there standard function can applied single vector process 2 elements per step?

for example, have vector:

> <- c(8, 4, 5, 5, 7, 10) 

and want subtract 2 neighbors elements:

> func(a, function (x1, x2) { x1-x2 })  [1] 4 -1 0 -2 -3 

in general if want process consecutive vector elements in pairs can first element in each pair with:

(first <- head(a, -1)) # [1] 8 4 5 5 7 

and can second element in each pair with

(second <- tail(a, -1)) # [1]  4  5  5  7 10 

then can perform operation want on consecutive elements. instance, here's operation:

first-second # [1]  4 -1  0 -2 -3 

here's product of consecutive elements:

first*second # [1] 32 20 25 35 70 

note operation pretty common there specialized function take differences of consecutive elements, diff.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -