代码之家  ›  专栏  ›  技术社区  ›  Max Lester

写入函数以计算向量中NA值的数量,同时忽略指定的索引

  •  1
  • Max Lester  · 技术社区  · 7 年前

    NA 向量中的值(在第一个参数中指定),在进行计数时也将忽略某些索引(在第二个参数中指定)。

    例如,如果我有 x = c(1,NA,3,4,NA,6,NA,8,9)

    我想给我们一个函数,比如 countNA(vector = x, ignore = c(5,7)) 并返回计数1(函数被告知忽略 x[5] x[7]

    countNA.2 = function(x, ignore){ 
        #define a function with arguments "x" (vector to be searched for NAs) 
        #and "ignore" vector indices to be ignored if NA
        count = c() #define empty vector to hold the counts of na in vector x
        t = c(1:9) #define a reference vector to represent possible indicies
        #(max vector length is 9)
        for (q in t){ #loop through our possible vector indicies
            ifelse(q %in% ignore, count[q] = 0, count[q] = is.na(x[q])) 
            #if index is in ignore vector, then set count[q] = 0 
            #else, set count[q] = TRUE for NA and FALSE otherwise
        }
        numoccurrences = sum(count) #after we're done, sum our count vector
        return(numoccurrences) #return
    } 
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   thelatemail    7 年前

    只需从向量中移除值,然后取 sum 属于 is.na :

    cntNA <- function(x, ignore) sum(is.na(x[-(ignore)]))
    cntNA(x, ignore=c(5,7))
    #[1] 1
    

    ignore if/else 条件:

    cntNA <- function(x, ignore=NULL) {
      if (is.null(ignore)) {
        sum(is.na(x))
      } else
      {
        sum(is.na(x[-(ignore)]))
      }
    }
    
    cntNA(x)
    #[1] 3
    
    cntNA(x, ignore=c(5,7))
    #[1] 1
    
    推荐文章