How to find the number of rows in a data.table where two or more column values meet a criteria in R?

R ProgrammingServer Side ProgrammingProgramming

Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

To find the number of rows in a data.table where two or more column values meet a criteria, we can follow the below steps −

• First of all, create a data.table object.
• Find the number of rows meeting a criteria.

Create data.table object

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

x<-rpois(20,1)
y<-rpois(20,1)
z<-rpois(20,1)
library(data.table)
DT<-data.table(x,y,z)
DT

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

Output

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

Find the number of rows meeting a criteria

Use Count:=.N to find the number of rows of DT where x=0, y=1, and z=1 −

x<-rpois(20,1)
y<-rpois(20,1)
z<-rpois(20,1)
library(data.table)
DT<-data.table(x,y,z)
DT[x==0 & y == 1 & z ==1,Count:=.N]
DT

Output

   x y z Count
1: 0 1 2 NA
2: 0 0 1 NA
3: 0 2 1 NA
4: 1 3 1 NA
5: 2 1 0 NA
6: 0 1 1 4
7: 2 1 1 NA
8: 0 0 0 NA
9: 0 1 1 4
10: 0 1 1 4
11: 0 2 1 NA
12: 0 0 3 NA
13: 3 1 1 NA
14: 2 0 1 NA
15: 2 1 0 NA
16: 0 1 1 4
17: 1 0 0 NA
18: 2 0 1 NA
19: 1 0 0 NA
20: 0 1 0 NA
Updated on 13-Aug-2021 15:30:33