user3755880
user3755880

Reputation: 375

R: ncol returning a NULL even though object is a matrix

I have a matrix that has only one column whose elements aren't entirely 0.

I use the following code to get the number of non-zero columns in a matrix:

ncol(matrix[, colSums(matrix) != 0])

This code returns the right number when the matrix has MORE than 1 non-zero column, but when the matrix has exactly 1 non-zero column, this code returns NULL.

I tried using this code and it seems to work fine:

length(which(colSums(matrix) != 0))

What could be the problem?

Upvotes: 0

Views: 291

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176658

You need to set drop = FALSE, otherwise [ will reduce its result to a vector if there is only one column.

ncol(matrix[, colSums(matrix) != 0, drop = FALSE])

Or just use NCOL, which accounts for this possibility.

NCOL(matrix[, colSums(matrix) != 0])

Upvotes: 3

Related Questions