编写函数来计算向量中 NA 值的数量,同时忽略指定的索引
Writing function to count number of NA values in vector while ignoring specified indices
我正在尝试编写一个函数来计算向量(在第一个参数中指定)中 NA
值的数量,该函数在进行计数时也会忽略一些索引(在第二个参数中指定) .
例如,如果我有
x = c(1,NA,3,4,NA,6,NA,8,9)
我想给我们一个函数
countNA(vector = x, ignore = c(5,7))
return 计数为 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
}
只需从向量中删除值并取 is.na
的 sum
:
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
我正在尝试编写一个函数来计算向量(在第一个参数中指定)中 NA
值的数量,该函数在进行计数时也会忽略一些索引(在第二个参数中指定) .
例如,如果我有
x = c(1,NA,3,4,NA,6,NA,8,9)
我想给我们一个函数
countNA(vector = x, ignore = c(5,7))
return 计数为 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
}
只需从向量中删除值并取 is.na
的 sum
:
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