How to replace zero with first non-zero occurring at the next position in an R data frame column?


To replace zero with first non-zero occurring at the next position in an R data frame column, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use na.locf function of zoo package to replace zero with first non-zero occurring at the next position in the data frame column.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x<-sample(0:5,20,replace=TRUE)
> df<-data.frame(x)
> df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Replace zero with first non-zero occurring at the next position

Using na.locf function of zoo package to replace zero with first non-zero occurring at the next position in column x of df −

 Live Demo

> library(zoo)
> df$x<-na.locf(with(df,ifelse(x==0,NA_real_,x)),fromLast=TRUE)
> df

Output

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

Updated on: 13-Aug-2021

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements