How to subset a data.table object in R by ignoring a value in one of the columns?



To subset a data.table object in R by ignoring a value in one of the columns, we can follow the below steps −

  • First of all, create a data.table object.

  • Then, use single square brackets to subset the data.table object by ignoring a value in one of the columns.

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table) x<-sample(1:3,25,replace=TRUE) y<-sample(1:4,25,replace=TRUE) z<-sample(1:3,25,replace=TRUE) DT<-data.table(x,y,z) DT

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

 x y z 1: 1 1 1 2: 1 3 1 3: 1 4 3 4: 3 3 1 5: 1 4 1 6: 1 2 3 7: 1 3 2 8: 1 3 1 9: 2 4 3 10: 1 4 3 11: 3 3 1 12: 3 2 2 13: 3 1 2 14: 2 4 2 15: 3 3 1 16: 3 2 1 17: 1 1 3 18: 2 4 1 19: 3 4 2 20: 3 2 1 21: 2 2 1 22: 3 4 1 23: 3 3 1 24: 1 1 1 25: 2 4 1 x y z

Subset the data.table object by ignoring a value in one of the columns

Using single square brackets to subset the data.table object DT by ignoring 4 in column y as shown below −

library(data.table) x<-sample(1:3,25,replace=TRUE) y<-sample(1:4,25,replace=TRUE) z<-sample(1:3,25,replace=TRUE) DT<-data.table(x,y,z) DT[DT$y!=4,]

Output

 x y z 1: 1 1 1 2: 1 3 1 3: 3 3 1 4: 1 2 3 5: 1 3 2 6: 1 3 1 7: 3 3 1 8: 3 2 2 9: 3 1 2 10: 3 3 1 11: 3 2 1 12: 1 1 3 13: 3 2 1 14: 2 2 1 15: 3 3 1 16: 1 1 1
Updated on: 2021-11-10T06:57:38+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements