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
One possible way:
indices<-which(b<0)
b[indices]<-a[indices+1]