Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Trailing and Leading NA for each vector

Tags:

r

na

vector

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
like image 670
Afiq Johari Avatar asked Sep 15 '19 15:09

Afiq Johari


1 Answers

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))])
like image 93
akrun Avatar answered Sep 22 '22 14:09

akrun