Count the number of non-zero columns in a matrix

Viewed 471

I have a matrix mat. Some of the columns of mat are all zeros while some of the columns are non-zero. How can I count the columns which are non-zero?

mat<-matrix(rep(0,2*5),ncol=2)
mat[,1]=c(1,2,3,4,5)

The desired result is 1.

2 Answers

If you want the columns that have non-zero elements, meaning they may have zeros but not all the rows are zeros then the following works:

mat<-matrix(rep(0,2*5),ncol=2)
mat[,1]=c(1,2,3,4,5)

sum(colSums(mat!=0)!=0)
#> [1] 1

But if you want to find the column which have no zeros, look below. I am making an example to illustrate that better:

mat2<-matrix(rep(0,4*5),ncol=4)
mat2[,1]=c(0,2,3,4,5)
mat2[,2]=c(1,2,3,4,5)
mat2[,3]=c(0,0,0,-1,1)

sum(colSums(mat2!=0)!=0) #count of non-zero columns
#> [1] 3

sum(colSums(mat2!=0)==nrow(mat2)) #count of columns with no zeros
#> [1] 1

If you want to find out which columns are non-zero then use which instead of sum:

which(colSums(mat2!=0)!=0) #non-zero columns
#> [1] 1 2 3


which(colSums(mat2!=0)==nrow(mat2)) #columns with no zeros
#> [1] 2

We can use apply column-wise and count number of columns which have any non-zero value

sum(apply(mat != 0, 2, any))
#[1] 1

Or if you want columns with all non-zero values

sum(apply(mat != 0, 2, all))
Related