Replace for diff () for multiple columns

diff () calculates the difference between the values ​​in the vector for a given delay. Is there an equivalent function working 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 a delay of 1. This will be:

 (2 - 5), (3 - 4), (4 - 3)... 

This can be achieved using head () / tails () combinations on 2 vectors, but I was wondering if there is already a function that can do the same.

+7
source share
4 answers

There is no basic function that I know for this, but since gsk3 indicated that the taRifx package has this feature. I would advise you not to call the package in order to do something simple: you could do:

 v1[-1] - v2[-length(v2)] 

Or write your own storage function in .Rprofile

 shift.diff <- function(x, y) x[-1] - y[-length(y)] shift.diff(v1, v2) 
+9
source

Take a look at the shift command in the taRifx package.

 library(taRifx) shift(v1)-v2 

You will need to decide what you want to do with the last record (v1 loop or just do it NA). shift has options for all of these possibilities, as well as for changing the delay to be something other than 1.

+4
source

If you are using the xts / zoo time series object, simply subtract the backward series:

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

The embed function will create the shifted vectors in matrix form. If you select the first column, it is an unmixed but abbreviated-one-at-the-end vector, and the second column is the shifted and shortened-by-one-at-the-start 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 
+2
source

All Articles