Alexandros
Alexandros

Reputation: 333

lagged difference with 2 vectors

I need a function to calculate difference between 2 variables and than its change over 1 lagged period of one of those variables. Formula looks like this:

enter image description here

Is there any simple way to achieve this without using more complex looping? I used diff function for regular percentage change of one vector like this:

pcchange = function(x){ c( NA, diff(x)/x[-length(x)] ) }

Is there any simple way by editing this function or example?

Upvotes: 1

Views: 273

Answers (1)

Hack-R
Hack-R

Reputation: 23216

An easy, vectorized, way to construct this would be to use dplyr. You could use the lead or lag functions.

vec1 <- seq(1,10)
vec2 <- seq(5,24,2)

library(dplyr)

df1 <- data.frame(vec1, vec2, lag_diff=((lead(vec1)-lead(vec2))/vec2))

df1
   vec1 vec2   lag_diff
1     1    5 -1.0000000
2     2    7 -0.8571429
3     3    9 -0.7777778
4     4   11 -0.7272727
5     5   13 -0.6923077
6     6   15 -0.6666667
7     7   17 -0.6470588
8     8   19 -0.6315789
9     9   21 -0.6190476
10   10   23         NA

Upvotes: 2

Related Questions