2

Assume I have the following df:

df <- data.frame(day = c(1:8), value= c(10, 25, NA, 7, NA, NA, 20, NA))

    Day     Value
1     1        10
2     2        25
3     3        NA
4     4         7
5     5        NA
6     6        NA
7     7        20
8     8        NA

I'm looking for a solution to replace NA in 'Value' column with the most recent previous non-NA value. The desired output will be:

    Day     Value
1     1        10
2     2        25
3     3        25
4     4         7
5     5         7
6     6         7
7     7        20
8     8        20
Agnes Lee
  • 322
  • 1
  • 12

2 Answers2

3

In base you can use ave in combination with cumsum to fill down.

df$value <- ave(df$value, cumsum(!is.na(df$value)), FUN = function(x) x[1])
df
#  day value
#1   1    10
#2   2    25
#3   3    25
#4   4     7
#5   5     7
#6   6     7
#7   7    20
#8   8    20
GKi
  • 37,245
  • 2
  • 26
  • 48
0

There are a series of non-base solutions:

zoo::na.locf(df$Value)
data.table::nafill(df$Value)

naniar is also a package that is completely designed surrounding NA handling.

Daniel V
  • 1,305
  • 7
  • 23