- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
> 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 −
> 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
- Related Articles
- How to replace zero with previous value in an R data frame column?
- How to create a column of first non-zero value in each row of an R data frame?
- How to extract the first highest occurring value in an R data frame column?
- How to move a column from other position to first position in an R data frame?
- How to find the smallest number in an R data frame column excluding values zero or less?
- How to replace missing values with median in an R data frame column?
- How to replace a complete column in an R data frame?
- How to randomly replace values in an R data frame column?
- How to find the number of values in a column of an R data frame that are not zero?
- How to replace numbers written in words with numbers in an R data frame column?
- How to replace space between two words with underscore in an R data frame column?
- How to replace words in a dichotomous column for an R data frame with numbers?\n
- How to subset non-duplicate values from an R data frame column?
- How to create a column of first non-zero value in each row of a data.table object in R?
- How to replace NA with 0 and other values to 1 in an R data frame column?

Advertisements