
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Replacement Column with Multiple Conditions in R Data Frame
To create a replacement column with multiple conditions and NA in R data frame, we can follow the below steps −
First of all, create a data frame.
Then, use nested ifelse function to create a replacement column with multiple conditions.
Example
Create the data frame
Let’s create a data frame as shown below −
x<-sample(c(NA,rpois(2,2)),25,replace=TRUE) df<-data.frame(x) df
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x 1 2 2 NA 3 2 4 2 5 2 6 2 7 2 8 NA 9 2 10 NA 11 2 12 NA 13 2 14 2 15 NA 16 NA 17 NA 18 2 19 2 20 NA 21 2 22 2 23 NA 24 NA 25 2
Replace column with multiple conditions
Using nested ifelse function to create a replacement column for column x with multiple conditions as shown below −
x<-sample(c(NA,rpois(2,2)),25,replace=TRUE) df<-data.frame(x) df$Replaced<-ifelse(df$x %in% 1,"5",ifelse(df$x %in% 2,"10",NA)) df
Output
x Replaced 1 0 NA 2 4 NA 3 0 NA 4 NA NA 5 0 NA 6 NA NA 7 NA NA 8 4 NA 9 0 NA 10 4 NA 11 4 NA 12 0 NA 13 NA NA 14 0 NA 15 0 NA 16 NA NA 17 NA NA 18 4 NA 19 0 NA 20 NA NA 21 0 NA 22 4 NA 23 NA NA 24 NA NA 25 4 NA
Advertisements