user3091668
user3091668

Reputation: 2310

Count numerical values in each column in R

I would like to count the numeric values in each collumn in my data frame (all):

NE001710    NE001360    NE001398    NE001380    NE001707
-0.12        -0.61       -0.61        -0.02       0.13
-0.58        -0.43       -0.24        -0.27      -0.47
  NA          0.19       -0.37        -0.14      -0.53
  NA         -0.13       -0.27        -0.38       0.05
  NA          NA          0.32        -0.34       0.01

The expected output can be something like that: res <- c("2","4","5","5","5")

Cheers!

Upvotes: 0

Views: 82

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

If you already know that all of your columns contain only numeric data and NA values, then you really just want to count the number of non-NA values, which can easily be done like this:

colSums(!is.na(all))
# NE001710 NE001360 NE001398 NE001380 NE001707 
#        2        4        5        5        5 

Alternatively, you can do:

## sapply(all, function(x) length(na.omit(x)))
vapply(all, function(x) length(na.omit(x)), 1L)
# NE001710 NE001360 NE001398 NE001380 NE001707 
#        2        4        5        5        5

Upvotes: 2

Related Questions