Process pairs of elements in a vector

121 views Asked by At

Is there any standard function that can be applied to a single vector to process two elements per step?

For example, we have the vector:

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

and we want to subtract two neighbors elements:

> func(a, function (x1, x2) { x1-x2 })

[1] 4 -1 0 -2 -3
1

There are 1 answers

1
josliber On BEST ANSWER

In general if you want to process consecutive vector elements in pairs you can get the first element in each pair with:

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

And you can get the second element in each pair with

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

Then you can perform any operation you want on the consecutive elements. For instance, here's your operation:

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

Here's the product of consecutive elements:

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

Note that your operation is actually pretty common so there is a specialized function to take the differences of consecutive elements, diff.