0

I am looking for a tidyverse-based solution to this problem. All I have seen previously has been data.table.

I want to carry forward the last observation, but for only one cycle. Below is the example. I have searched and it looks like most of the tools carry forward the entire stretch of NAs. Here is what I would like:

x <-    c(NA, 3, 4, 5, 6, NA, NA, NA, 7, 8, 9 ,10, NA, NA, NA, 11, NA, 13)

goal <- c(NA, 3, 4, 5, 6, 6, NA, NA, 7, 8, 9 ,10, 10, NA, NA, 11, 11, 13)

As you can see, only the first instance of NA in each stretch (disregarding leading NAs) is replaced with the last observation. For our data, that has been shown to be the most reliable method, but I cannot figure out how to do this in R. Thanks!

I've tried using both the "zoo" and "imputeTS" packages (na.locf() & na_locf() functions, respectively). It doesn't appear that either have this ability...

CG_2
  • 13
  • 3
  • `coalesce(x, lag(x))` could be a `dplyr` alternative. At least it works for your example (`all.equal(coalesce(x, lag(x)), goal)`) – Henrik Jan 20 '23 at 22:14
  • The most common situation is that if the gap is longer than a certain amount then you don't want to fill it at all. The maxgap argument of na.locf and na.locf0 does that. – G. Grothendieck Jan 20 '23 at 23:01

0 Answers0