r - lagged difference with 2 vectors -


i need function calculate difference between 2 variables , change on 1 lagged period of 1 of variables. formula looks this:

enter image description here

is there simple way achieve without using more complex looping? used diff function regular percentage change of 1 vector this:

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

is there simple way editing function or example?

an easy, vectorized, way construct use dplyr. use 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 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -