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


To find the percentage 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 along with nrow function to find the percentage of zeros in each column.

Example 1

Create the matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(100,2),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   1    1    0
[2,]  1   1    3    3
[3,]  2   1    4    0
[4,]  1   2    1    0
[5,]  2   0    2    1
[6,]  2   2    1    2
[7,]  4   4    3    5
[8,]  0   2    5    2
[9,]  1   0    5    1
[10,] 0   0    1    5
[11,] 1   3    2    2
[12,] 0   2    0    4
[13,] 2   4    2    2
[14,] 2   3    1    3
[15,] 1   1    2    3
[16,] 1   3    1    2
[17,] 4   2    2    2
[18,] 1   0    2    3
[19,] 6   0    4    3
[20,] 1   0    1    0
[21,] 2   4    0    0
[22,] 2   2    3    2
[23,] 3   1    2    1
[24,] 2   0    1    1
[25,] 3   4    0    0

Find the percentage of zeros

Using colSums function along with nrow function to find the percentage of zeros in each column of matrix M1 −

M1<-matrix(rpois(100,2),ncol=4)
(colSums(M1==0)/nrow(M1))*100

Output

[1] 12 28 12 24

Example 2

Create the matrix

Let’s create a matrix as shown below −

M2<-matrix(sample(0:10,100,replace=TRUE),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,]   5   0    2    8
[2,]   7  10    7    9
[3,]   4   3    2    2
[4,]   7   6    2    1
[5,]   3   2   10    4
[6,]   2   2    7    1
[7,]  10   3    6    1
[8,]   9   3    7    8
[9,]   7   6    5    4
[10,] 10   9    0    3
[11,]  5   0    7    6
[12,]  1   7    1    8
[13,]  0   9    6    5
[14,]  4   0    6    7
[15,]  7  10    0    1
[16,]  5   9    7    1
[17,]  8   3    7   10
[18,]  4   9    6    8
[19,]  6  10   10    1
[20,]  8   0   10    5
[21,]  7   4    0   10
[22,]  4   3    5   10
[23,]  2   7    0   10
[24,]  3   2    6   10
[25,]  4   0    9    3

Find the percentage of zeros

Using colSums function along with nrow function to find the percentage of zeros in each column of matrix M2 −

M2<-matrix(sample(0:10,100,replace=TRUE),ncol=4)
(colSums(M2==0)/nrow(M2))*100

Output

[1] 4 20 16 0

Updated on: 10-Nov-2021

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements