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

时间:2017-09-27 23:02:40

标签: r function vector na ignore

我正在尝试编写一个函数来计算向量中的NA值的数量(在第一个参数中指定),它在计数时也会忽略某些索引(在第二个参数中指定)。 / p>

例如,如果我有     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 个答案:

答案 0 :(得分:1)

只需从矢量中删除值,然后选择sum的{​​{1}}:

is.na

如果您想说明未指定cntNA <- function(x, ignore) sum(is.na(x[-(ignore)])) cntNA(x, ignore=c(5,7)) #[1] 1 ,只需添加ignore条件:

if/else