- Trending Categories
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 create a replacement column with multiple conditions and NA in data.table object in R?
To create a replacement column with multiple conditions and NA in data.table object in R, we can follow the below steps −
First of all, create a data.table object.
Then, use nested ifelse function to create a replacement column with multiple conditions.
Example
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-sample(c(NA,rpois(2,1)),25,replace=TRUE) DT<-data.table(x) DT
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x 1: NA 2: NA 3: 2 4: 0 5: 2 6: 2 7: 0 8: NA 9: 0 10: 0 11: 0 12: NA 13: 2 14: NA 15: 0 16: 0 17: 2 18: 2 19: 2 20: 0 21: 2 22: NA 23: NA 24: 2 25: 0 x
Replace column with multiple conditions
Using nested ifelse function to create a replacement column for column x with multiple conditions as shown below −
library(data.table) x<-sample(c(NA,rpois(2,1)),25,replace=TRUE) DT<-data.table(x) DT$Replaced<-ifelse(DT$x %in% 0,"0",ifelse(DT$x %in% 2,"1",NA)) DT
Output
x Replaced 1: NA <NA> 2: NA <NA> 3: 2 1 4: 0 0 5: 2 1 6: 2 1 7: 0 0 8: NA <NA> 9: 0 0 10: 0 0 11: 0 0 12: NA <NA> 13: 2 1 14: NA <NA> 15: 0 0 16: 0 0 17: 2 1 18: 2 1 19: 2 1 20: 0 0 21: 2 1 22: NA <NA> 23: NA <NA> 24: 2 1 25: 0 0 x Replaced
- Related Articles
- How to create a replacement column with multiple conditions and NA in R data frame?
- How to remove rows in a data.table object with NA's in R?
- How to create a correlation matrix by a categorical column in data.table object in R?
- How to add a column to data.table object in R?
- How to subset a data.table object in R by specifying columns that contains NA?
- How to remove repeated column names in a data.table object in R?
- How to standardize data.table object column by group in R?
- How to create NA column for a contingency table in R?
- How to standardize multiple columns not all in data.table object in R?
- How to multiply corresponding row values in a data.table object with single row data.table object in R?
- How to create a column of first non-zero value in each row of a data.table object in R?
- How to create a subset using character column with multiple matches in R?
- How to create pivot table with sum for data stored in data.table object in R?
- How to separate a specific text and the remaining text in data.table object column in R?
- How to separate two values in single column in data.table object in R?

Advertisements