You could generalize this to an arbitrary number of vectors. The entered vectors are listed which facilitates to compare their lengths. Only if the variance is zero, we may cbind and count NAs in rows, otherwise we return 0.
f <- \(...) {
lst <- list(...)
ln <- length(lst)
stopifnot(ln > 1L)
ls <- lengths(lst)
if (sum(ls) == 0L) { ## all lengths null
0L
}
else if (var(ls) != 0) { ## different lengths
warning("vectors are not of equal length")
0L
} else {
sum(rowSums(is.na(do.call(cbind, lst))) == ln)
}
}
Usage
f(x, y)
# [1] 2
f(x, y[1:3])
# [1] 0
# Warning message:
# In f(x, y[1:3]) : vectors are not of equal length
f(x, y, z)
# [1] 7
f(x, y[1:3], z)
# [1] 0
# Warning message:
# In f(x, y[1:3], z) : vectors are not of equal length
f(x, y, NULL)
# [1] 0
# Warning message:
# In f(x, y, NULL) : vectors are not of equal length
f(NULL, NULL)
# [1] 0
f(x)
f()
f(NULL)
# Error in f(NULL) : length(lst) > 1L is not TRUE
Data:
x <- c(1L, 1L, 1L, 1L, NA, NA, NA, NA, 1L, NA, 1L, NA, 1L, NA, 1L,
1L, NA)
y <- c(NA, NA, NA, 1L, 1L, 1L, 1L, 1L, NA, 1L, 1L, 1L, 1L, NA, NA,
NA, NA)
z <- c(1L, NA, 1L, NA, NA, NA, 1L, 1L, NA, NA, NA, NA, NA, NA, NA,
1L, NA)