- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements