How to find the number of zeros in each column of a matrix in R?


To find the number of zeros in each column of a matrix in R, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use colSums function to find the number of zeros in each column.

Example 1

Create the matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(100,1),ncol=4)
M1

Output

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

    [,1] [,2] [,3] [,4]
[1,]  2   0    1    1
[2,]  0   0    0    1
[3,]  2   1    2    3
[4,]  2   0    0    0
[5,]  1   0    1    1
[6,]  2   5    1    0
[7,]  1   2    2    0
[8,]  0   2    0    1
[9,]  1   1    2    1
[10,] 4   0    0    1
[11,] 3   1    0    0
[12,] 2   1    1    1
[13,] 1   0    1    1
[14,] 1   1    1    2
[15,] 0   0    1    0
[16,] 2   2    0    0
[17,] 3   1    1    1
[18,] 1   2    1    1
[19,] 1   1    1    1
[20,] 3   0    1    0
[21,] 1   0    3    2
[22,] 2   0    0    0
[23,] 2   2    0    2
[24,] 0   0    1    2
[25,] 1   0    2    1

Find the number of zeros

Using colSums function to find the number of zeros in each column of matrix M1 −

M1<-matrix(rpois(100,1),ncol=4)
colSums(M1==0)

Output

[1] 4 12 8 8

Example 2

Create the matrix

Let’s create a matrix as shown below −

M2<-matrix(round(rnorm(100),0),ncol=4)
M2

Output

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

     [,1] [,2] [,3] [,4]
[1,]   0   1    1    -3
[2,]   1  -1   -1    -1
[3,]  -1   0    0     1
[4,]  -3  -1   -1     2
[5,]   1   0    1     0
[6,]   0  -1   -1     1
[7,]   1   0    2    -1
[8,]   0   1   -1    -2
[9,]  -2  -2   -1     2
[10,] -1   1   -1     1
[11,] -1   0    0     0
[12,]  1   0    1    -1
[13,]  1   0    0     1
[14,] -1   1   -1     0
[15,]  1   0   -1     1
[16,]  3   1   -1    -1
[17,]  1   1   -1    -1
[18,]  0   0   -1    -2
[19,]  0   1    0     0
[20,]  1   0    1     0
[21,]  1   1    1    -1
[22,]  1   0    1     0
[23,]  1   0    0     1
[24,]  2   2   -2     0
[25,]  1   0   -1     0

Find the number of zeros

Using colSums function to find the number of zeros in each column of matrix M2 −

M2<-matrix(round(rnorm(100),0),ncol=4)
colSums(M2==0)

Output

[1] 5 12 5 8

Updated on: 15-Nov-2021

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements