How to fill in the preceding numbers whenever there is a 0 in R?

numbers, r, replace, sequence

Solution

n2 <- n1[cummax(seq_along(n1) * (n1 != 0))]

Problem

I have a string of numbers: ``` n1 = c(1, 1, 0, 6, 0, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0) ``` I need to replace 0 with the corresponding number right in front of it to get: ``` n2 = c(1, 1, 1, 6, 6, 6, 10, 10, 11, 12, 12, 12, 19, 23, 23, 23) ``` How can I get from n1 to n2? Thanks in advance!

Original source