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
In general if you want to process consecutive vector elements in pairs you can get the first element in each pair with:
And you can get the second element in each pair with
Then you can perform any operation you want on the consecutive elements. For instance, here's your operation:
Here's the product of consecutive elements:
Note that your operation is actually pretty common so there is a specialized function to take the differences of consecutive elements,
diff
.