Robert Kubrick
Robert Kubrick

Reputation: 8713

Replacement for diff() for multiple columns

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.

Upvotes: 7

Views: 1494

Answers (4)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

If you're using an xts/zoo time-series object, just subtract the lagged series:

x <- .xts(cbind(v1,v2), 1:length(v1))
x$v1-lag(x$v2)

Upvotes: 2

IRTFM
IRTFM

Reputation: 263362

The embed function will create shifted vectors in matrix form. If you pick the first column it is the unshifted but shortened-by-one-at-the-end vector and the second column is the shifted and shortened-by-one-at-the-beginning vector.

embed(v1,2)[,1] -embed(v2,2)[,2]
#[1] -3 -1  1  3  2

embed(v1, 2)
     [,1] [,2]
[1,]    2    1
[2,]    3    2
[3,]    4    3
[4,]    5    4
[5,]    3    5

Upvotes: 2

Tyler Rinker
Tyler Rinker

Reputation: 109874

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)

Upvotes: 9

Ari B. Friedman
Ari B. Friedman

Reputation: 72741

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.

Upvotes: 4

Related Questions