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

前端 未结 4 775
走了就别回头了
走了就别回头了 2020-12-05 00:23

Say I have the following R data.frame ZZZ:

( ZZZ <- structure(list(n = c(1, 2, NA), m = c(6, NA, NA), o = c(7, 8, 
8)), .Names = c(\         


        
4条回答
  •  攒了一身酷
    2020-12-05 01:06

    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
    

提交回复
热议问题