How to fill NA values with previous values in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To fill NA values with next and previous values, we can use na.locf function of zoo package with fromLast = TRUE. This is the situation of a column as shown below −

x
0
NA
NA
1
1
NA
0
1

The output after filling NA values with next and previous values will be −

x
0
0
0
1
1
1
0
1

Consider the below data frame −

Example

 Live Demo

x1<-sample(c(NA,rpois(2,1)),20,replace=TRUE)
x2<-sample(c(NA,rpois(2,5)),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1

Output

   x1  x2
1  0    1
2  NA   6
3  NA   NA
4  1    6
5  1    NA
6  NA   NA
7  0    6
8  1    1
9  NA   6
10 1    NA
11 1    6
12 NA   NA
13 NA   6
14 1    NA
15 1    1
16 NA   6
17 NA   6
18 NA   NA
19 1    NA
20 1    6

Loading zoo package and replacing NA values with previous values in df1 −

Example

library(zoo)
na.locf(na.locf(df1),fromLast=TRUE)

Output

   x1 x2
1  0  1
2  0  6
3  0  6
4  1  6
5  1  6
6  1  6
7  0  6
8  1  1
9  1  6
10 1  6
11 1  6
12 1  6
13 1  6
14 1  6
15 1  1
16 1  6
17 1  6
18 1  6
19 1  6
20 1  6

Example

 Live Demo

y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(2)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2

Output

        y1       y2
1  -0.4569616   NA
2   NA         -1.014162
3   NA         -1.014162
4  -0.4569616  -1.014162
5  -0.4569616  NA
6   0.2828478  1.282601
7  -0.4569616  NA
8   0.2828478  NA
9   0.2828478  -1.014162
10  NA          1.282601
11  0.2828478  -1.014162
12 -0.4569616   1.282601
13  0.2828478  -1.014162
14  NA         -1.014162
15  0.2828478  -1.014162
16  NA         NA
17 -0.4569616  NA
18 -0.4569616  -1.014162
19  0.2828478  -1.014162
20  NA         -1.014162

Replacing NA values with previous values in df2 −

Example

na.locf(na.locf(df2),fromLast=TRUE)

Output

        y1         y2
2  -0.4569616   -1.014162
3  -0.4569616   -1.014162
4  -0.4569616   -1.014162
5  -0.4569616   -1.014162
6   0.2828478    1.282601
7  -0.4569616    1.282601
8   0.2828478    1.282601
9   0.2828478   -1.014162
10  0.2828478    1.282601
11  0.2828478   -1.014162
12 -0.4569616    1.282601
13  0.2828478   -1.014162
14  0.2828478   -1.014162
15  0.2828478   -1.014162
16  0.2828478   -1.014162
17 -0.4569616   -1.014162
18 -0.4569616   -1.014162
19  0.2828478   -1.014162
20  0.2828478   -1.014162
raja
Published on 10-Feb-2021 06:08:28
Advertisements