diff() calculates the difference between values in a vector at a specified lag. Is there an equivalent function that works on two vectors? For example, I have:
v1 = c(1, 2, 3, 4, 5, 3)
v2 = c(5, 4, 3, 2, 1, 0)
I need to calculate the difference between each value of v1 and v2 at lag 1. That would be:
(2 - 5), (3 - 4), (4 - 3)...
This can be achieved using combinations of head()/tails() on the 2 vectors, but I was wondering if there is already a function that can do the same.
There's no base function I know of to do this but as gsk3 pointed out the taRifx package has this capability. I would advise against calling a package to do something this simple: You could do:
v1[-1] - v2[-length(v2)]
Or write your own function for storage in .Rprofile
shift.diff <- function(x, y) x[-1] - y[-length(y)]
shift.diff(v1, v2)
Take a look at the shift
command in the taRifx
package.
library(taRifx)
shift(v1)-v2
You'll have to decide what you want to do with the last entry (cycle v1 or just make it NA). shift
has options for all of those possibilities, as well as for changing the lag to be something other than 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With