
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
Find Number of Zeros in Each Row of a Data Table Object in R
To find the number of zeros in each row of a data.table object in R, we can follow the below steps −
First of all, create a data.table object.
Then, use rowSums function to find the number of zeros in each row of the data.table object.
Example
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-sample(0:3,25,replace=TRUE) y<-sample(0:3,25,replace=TRUE) z<-sample(0: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 2 1 2: 1 1 3 3: 0 0 2 4: 3 3 3 5: 2 0 3 6: 1 0 1 7: 2 3 3 8: 2 3 3 9: 3 1 2 10: 0 0 0 11: 2 3 0 12: 3 3 0 13: 0 0 2 14: 2 3 0 15: 0 3 0 16: 3 3 1 17: 2 1 3 18: 1 3 0 19: 3 0 0 20: 1 2 2 21: 2 1 1 22: 0 2 2 23: 0 0 3 24: 3 2 2 25: 1 2 1 x y z
Find the number of zeros in each row
Using rowSums function to find the number of zeros in each row of the data.table object DT −
library(data.table) x<-sample(0:3,25,replace=TRUE) y<-sample(0:3,25,replace=TRUE) z<-sample(0:3,25,replace=TRUE) DT<-data.table(x,y,z) DT$Total_0s<-rowSums(DT==0) DT
Output
x y z Total_0s 1: 1 2 1 0 2: 1 1 3 0 3: 0 0 2 2 4: 3 3 3 0 5: 2 0 3 1 6: 1 0 1 1 7: 2 3 3 0 8: 2 3 3 0 9: 3 1 2 0 10: 0 0 0 3 11: 2 3 0 1 12: 3 3 0 1 13: 0 0 2 2 14: 2 3 0 1 15: 0 3 0 2 16: 3 3 1 0 17: 2 1 3 0 18: 1 3 0 1 19: 3 0 0 2 20: 1 2 2 0 21: 2 1 1 0 22: 0 2 2 1 23: 0 0 3 2 24: 3 2 2 0 25: 1 2 1 0 x y z Total_0s
Advertisements