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
}