I have some vectors in the following format
v1 <- c(NA,NA,NA,10,10,10,10)
v2 <- c(NA,NA, 3, 3, 3,NA,NA)
v3 <- c( 5, 5, NA,NA,NA,NA,NA)
For each vector I want to calculate how many leading NAs and trailing NAs.
For v1, LeadNA = 3, TrailNA = 0
For v2, LeadNA = 2, TrailNA = 2
For v3, LeadNA = 0, TrailNA = 5
1) Cumsum - An option would be to create a logical vector with cumsum
on the presence of non-NA elements and get the sum
(base R
- No packages used)
f1 <- function(vec, trail = FALSE) {
if(trail) {
vec <- rev(vec)
}
sum(!cumsum(!is.na(vec)))
}
f1(v1)
#[1] 3
f1(v1, TRUE)
#[1] 0
sapply(mget(paste0("v", 1:3)), f1)
# v1 v2 v3
# 3 2 0
sapply(mget(paste0("v", 1:3)), f1, TRUE)
# v1 v2 v3
# 0 2 5
2 rle - Another base R
option is rle
(No packages are used)
with(rle(is.na(v2)), lengths[values & seq_along(values) %in% c(1, length(values))])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With