Search code examples
rreplacedifflag

In R: How to create a vector of lagged differences but keep the original value for negative differences without using loops


I have a vector in R of the form:

> a <- c(1,3,5,7,9,11,1,3,5,7,9,11,1,3,5,7,9,11)
> a
 [1]  1  3  5  7  9 11  1  3  5  7  9 11  1  3  5  7  9 11

I can take the lagged differences like this:

b <- diff(a)
> b
 [1]   2   2   2   2   2 -10   2   2   2   2   2 -10   2   2   2   2   2

But I would like the negative differences to be replaced by the original values in the vector a. Or, in this case the -10's to be replaced by the 1's.

Is there a way to do this without looping though the vectors? Thanks


Solution

  • One possible way:

        indices<-which(b<0)
        b[indices]<-a[indices+1]