Simple method of counting non-NAs in column of data String

na, r

Solution

For a `data.frame` you can get it using `colSums` and `is.na`:

set.seed(45)
df <- data.frame(matrix(sample(c(NA,1:5), 50, replace=TRUE), ncol=5))
#    X1 X2 X3 X4 X5
# 1   3  2 NA  2 NA
# 2   1  5  1  1  4
# 3   1  1  3  2  3
# 4   2  2  3  5  3
# 5   2  2  5  2  2
# 6   1  2 NA  3  3
# 7   1  5  5  5  2
# 8   3 NA  4  1  5
# 9   1  2  3 NA  1
# 10 NA  1  1  2  2

colSums(!is.na(df))
# X1 X2 X3 X4 X5 
#  9  9  8  9  9 

Problem

I am trying to find a simple way of counting the non missing cases in a column of a data frame. I have used the function: ``` foo<- function(x) { sum(!is.na(x)) } ``` and then apply it to a data frame via sapply() ``` stats$count <- sapply(OldExaminee, foo2, simplify=T) ``` Although this is working fine, I am just in disbelieve that there isn't a simpler way of counting, i.e. something in the base set of function. Any ideas?

Original source

Related problems