Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain a position of last non-zero element

Tags:

I've got a binary variable representing if event happened or not:

event <- c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0)

I need to obtain a variable that would indicate the time when the last event happened. The expected output would be:

last_event <- c(0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13)

How can I obtain that with base R, tidyverse or any other way?

like image 876
jakes Avatar asked Apr 11 '19 14:04

jakes


Video Answer


2 Answers

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

cummax(seq_along(event) * event)
like image 142
mgiormenti Avatar answered Oct 10 '22 17:10

mgiormenti


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)$lengths
nonzeros = 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)
like image 42
Konrad Rudolph Avatar answered Oct 10 '22 17:10

Konrad Rudolph