0

i have table with missing values, how can i fill the next 3 missing values with the latest available value?

as example i use this table, I want to fill 2021 May - 2021 Jul value with the latest non-missing data which is 249.

Date        value
2021 Jan    500
2021 Feb    2340
2021 Mar    3000
2021 Apr    249
2021 May    NA
2021 Jun    NA
2021 Jul    NA
Dana Ann
  • 11
  • 2

2 Answers2

0

Try with the zoo library:

library(zoo)
na.locf(na.locf(df))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

Another option is with fill:

library(tidyr)
df %>%
  fill(value)

You could specify the direction in which to fill with .direction = ... but "down" is the default so in your case need not be specified

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34