How to fill in the preceding numbers whenever there is a 0 in R?
问题 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! 回答1: n2 <- n1[cummax(seq_along(n1) * (n1 != 0))] 回答2: Try na.locf() from the package zoo : library(zoo) n1 <- c(1, 1, 0, 6, 0, 0, 10, 10, 11, 12, 0, 0, 19, 23, 0, 0) n1[n1 == 0] <- NA na.locf(n1) ## [1] 1 1 1 6 6 6