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

Updated on: 12-Nov-2021

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements