How to obtain a position of last non-zero element How to obtain a position of last non-zero element r r

How to obtain a position of last non-zero element


Taking advantage of the fact that you have a binary vector, the following gives your desired output:

cummax(seq_along(event) * event)


Whenever you need to fill repetitions with a value, think run-length encoding.

In this case, you can determine the run lengths and then repeat the indices of count == 0 an according number of times:

lengths = rle(event == 0)$lengthsnonzeros = which(event != 0)runs = c(0, rep(nonzeros, each = 2))result = rep(runs, lengths)

Alternative, substitute the runs in the RLE and then inverse it:

rle = rle(event == 0)nonzeros = which(event != 0)rle$values = c(0, rep(nonzeros, each = 2))result = inverse.rle(rle)


You can also do somthing like this-

> zero.locf <- function(x) {  v <- x!=0  c(0, x[v])[cumsum(v)+1]}> zero.locf(1:length(event)*event)[1]  0  0  0  0  5  5  5  5  5  5  5  5 13 13 13 13