Home > front end >  How do I count only non-empty columns in R, while included columns with sparse NA?
How do I count only non-empty columns in R, while included columns with sparse NA?

Time:09-28

I have a matrix as such:

A      B      C     D
1      4      5     NA
43     3      NA    NA
85     NA     43    NA
4      2      NA    NA

I am trying to figure out how to count the number of non empty columns (In this case it would = 3). However if I do ncol(df) I get 4. How can I count only the columns that are not completely empty (idealy with base R or Tidyverse (trying not to use too many imported packages)?

CodePudding user response:

We may build a logical matrix with is.na, get the colSums, convert to a logical. vector (> 0) and get the sum

sum(colSums(!is.na(m1)) > 0)
[1] 3

Or may also use Filter on a data.frame and get the ncol

ncol(Filter(function(x) any(!is.na(x)), as.data.frame(m1)))
[1] 3

data

m1 <- structure(c(1L, 43L, 85L, 4L, 4L, 3L, NA, 2L, 5L, NA, 43L, NA, 
NA, NA, NA, NA), .Dim = c(4L, 4L), .Dimnames = list(NULL, c("A", 
"B", "C", "D")))

CodePudding user response:

We could use sum and sapply

sum(sapply(df, function(y) sum(length(which(is.na(y))))>0))

output:

[1] 3
  • Related