Search code examples
rtidyverseradix

How to obtain a position of last non-zero element


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?


Solution

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

    cummax(seq_along(event) * event)