Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for diff() for multiple columns

Tags:

r

diff

zoo

xts

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.

like image 638
Robert Kubrick Avatar asked Mar 30 '12 15:03

Robert Kubrick


2 Answers

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)
like image 78
Tyler Rinker Avatar answered Sep 19 '22 02:09

Tyler Rinker


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.

like image 44
Ari B. Friedman Avatar answered Sep 21 '22 02:09

Ari B. Friedman