4

I have a large dataset and the shorter version of that is as below

 Col1         Col2
 0            1
 1            0.9971
 4            NA
 6            NA
 7            NA
 14           NA
 18           0.9951
 22           NA
 25           NA
 46           0.9941
 57           NA
 59           NA
 60           0.9921

For those missing values in Col2, I want the NAs replaced with the value above it from the same column Col2. The final dataset would look like this below.

    Col1         Col2
 0            1
 1            0.9971
 4            0.9971
 6            0.9971
 7            0.9971
 14           0.9971
 18           0.9951
 22           0.9951
 25           0.9951
 46           0.9941
 57           0.9941
 59           0.9941
 60           0.9921
bison2178
  • 747
  • 1
  • 8
  • 22

1 Answers1

5

There is a function na.locf (NA last observation carried forward) to do this in the package zoo:

> zoo::na.locf(df)
   Col1   Col2
1     0 1.0000
2     1 0.9971
3     4 0.9971
4     6 0.9971
5     7 0.9971
6    14 0.9971
7    18 0.9951
8    22 0.9951
9    25 0.9951
10   46 0.9941
11   57 0.9941
12   59 0.9941
13   60 0.9921
C. Braun
  • 5,061
  • 19
  • 47