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'll try to be the one to offer a pure R solution:
example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0);
cs = cumsum(example!=0);
mch = match(cs, cs);
desired.output = example[mch];
print(cbind(example,desired.output))
UPD: It may be faster to calculate mch
above with
mch = findInterval(cs-1,cs)+1
UPD2: I like the answer by @Roland. It can be shortened to two lines:
NN = (example != 0);
desired.output = c(example[1], example[NN])[cumsum(NN) + 1L];