Counting non NAs in a data frame; getting answer as a vector

强颜欢笑 提交于 2019-11-27 19:05:17

Try this:

# define "demo" dataset
ZZZ <- data.frame(n=c(1,2,NA),m=c(6,NA,NA),o=c(7,8,8))
# apply the counting function per columns
apply(ZZZ, 2, function(x) length(which(!is.na(x))))

Having run:

> apply(ZZZ, 2, function(x) length(which(!is.na(x))))
n m o 
2 1 3 

If you really insist on returning a vector, you might use as.vector, e.g. by defining this function:

nonNAs <- function(x) {
    as.vector(apply(x, 2, function(x) length(which(!is.na(x)))))
    }

You could simply run nonNAs(ZZZ):

> nonNAs(ZZZ)
[1] 2 1 3
hadley
colSums(!is.na(x))

Vectorisation ftw.

For getting total no of missing values use sum(is.na(x)) and for colum-wise use colSums(is.na(x)) where x is varible that contain dataset

If you only want the sum total of NAs overall, then sum() with !is.na() will do it:

ZZZ <- data.frame(n = c(1, 2, NA), m = c(6, NA, NA), o = c(7, 8, 8))
sum(!is.na(ZZZ))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!