Max Lester
Max Lester

Reputation: 143

Writing function to count number of NA values in vector while ignoring specified indices

I am trying to write a function to count the number of NA values in a vector (specified in the first argument) that will also ignore some indices (specified in a second argument) when making the count.

For example, if I have x = c(1,NA,3,4,NA,6,NA,8,9)

I want to us a function like countNA(vector = x, ignore = c(5,7)) and return a count of 1 (the function is told to ignore x[5] and x[7]

This is what I've tried so far, but it isn't working:

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
} 

Upvotes: 1

Views: 548

Answers (1)

thelatemail
thelatemail

Reputation: 93813

Just remove the values from the vector and take the sum of is.na:

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

If you want to account for ignore not being specified, just add an if/else condition:

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

Upvotes: 1

Related Questions