I find it hard to come up with a fast solution to the following problem:
I have a vector of observations, which indicates the time of observation of certain phenomena. <
I suspect that your 0
values are actually NA values. Here I make them NA
and than use na.locf
(Last Observation Carried Forward) from package zoo:
example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0)
res <- example
#res[res==0] <- NA
#the same but faster
res <- res/res*res
library(zoo)
res <- na.locf(res, na.rm = FALSE)
res[is.na(res)] <- 0
cbind(example, res)
# example res
# [1,] 0 0
# [2,] 0 0
# [3,] 0 0
# [4,] 1 1
# [5,] 0 1
# [6,] 1 1
# [7,] 1 1
# [8,] 0 1
# [9,] 0 1
# [10,] 0 1
# [11,] -1 -1
# [12,] 0 -1
# [13,] 0 -1
# [14,] -1 -1
# [15,] -1 -1
# [16,] 0 -1
# [17,] 0 -1
# [18,] 1 1
# [19,] 0 1
# [20,] 0 1