Best way to reduce consecutive NAs to single NA
Posted
by
digEmAll
on Stack Overflow
See other posts from Stack Overflow
or by digEmAll
Published on 2012-09-28T15:15:08Z
Indexed on
2012/09/28
15:37 UTC
Read the original article
Hit count: 214
r
I need to reduce the consecutive NA's in a vector to a single NA, without touching the other values.
So, for example, given a vector like this:
NA NA 8 7 NA NA NA NA NA 3 3 NA -1 4
what I need to get, is the following result:
NA 8 7 NA 3 3 NA -1 4
Currently, I'm using the following function:
reduceConsecutiveNA2One <- function(vect){
enc <- rle(is.na(vect))
# helper func
tmpFun <- function(i){
if(enc$values[i]){
data.frame(L=c(enc$lengths[i]-1, 1), V=c(TRUE,FALSE))
}else{
data.frame(L=enc$lengths[i], V=enc$values[i])
}
}
Df <- do.call(rbind.data.frame,lapply(1:length(enc$lengths),FUN=tmpFun))
return(vect[rep.int(!Df$V,Df$L)])
}
and it seems to work fine, but probably there's a simpler/faster way to accomplish this task.
Any suggestions ?
Thanks in advance.
© Stack Overflow or respective owner