Replace the NA values in a column based on the previous values [closed]

I have this large dataframe/matrix with the values of air temperature in different timestamp.

> head(data)
        V2 V3   V9
1 20210101  0 13.4
2 20210101  5 13.4
3 20210101 10 13.2
4 20210101 15 13.1
5 20210101 20 13.0
6 20210101 25 12.8
...

Assume that the observation from 7 to 10 the V9’s values are all NA. I want to replace these NA values of the rows 7 to 10 with the previous observed value, which is 12.8 in this case. I tried these commands in RStudio using zoo package. (data is the dataframe of my dataset).

library(zoo)
na.locf(data$V9)

However, the results show that they are still NA values. No replacement. I also tried to use dyplr package for it with fill(), direction = “up” but no NA values are replaced. I simply think if I choose a specific column like that, the replacement does not care about the time frame. Or does it? Is there any trick here and what should I do? Kindly advise.

  • tidyr::fill(data, V9) should do the trick

    – 

  • ude direction down not up

    – 

  • 2

    You have to reassign the values, they are not replaced in-place, e.g. dat$V9 <- zoo::na.locf(dat$V9)

    – 

  • 1

    @AndreWildberg Thank you so much. It works. I did not know I had to re-assign it.

    – 

Leave a Comment