# LaVOZs

The World’s Largest Online Community for Developers

'; r - Changing NA value if matching a defined length - LavOzs.Com

I have this kind of data :

``````daynight
 NA NA NA NA  2  1 NA NA
``````

I want R to detect if there is a series of at least x `NA` and replace these by another value. For example if x=3 and the replacement value is 3 I want R to give me in output :

``````daynight
 3 3 3 3 2 1 NA NA
``````

Would you have any ideas?

We can use `rle`

``````daynight <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)
x <- 3
r <- 3
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
daynight
#  3  3  3  3  2  1 NA NA
``````

Taking another example :

``````daynight <- c(NA, NA, NA, 3,2,1, NA, NA, 1, NA, NA, NA, 1, NA, NA)
daynight[with(rle(is.na(daynight)), rep(lengths >= x & values, lengths))] <- r
#  3  3  3  3  2  1 NA NA  1  3  3  3  1 NA NA
``````

And here is another solution using the `zoo` package

``````library(zoo)

replace_consecutive_NAs <- function(x, nrNAs = 3, replaceBy = nrNAs){
x <- as.numeric(is.na(x))
indexes <- (rollapply(x, 3, prod, fill = 0, align = "left") +
rollapply(x, 3, prod, fill = 0, align = "right")) != 0
x[indexes] <- replaceBy
x
}

x <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)

replace_consecutive_NAs(x, 3, 999)

 999 999 999 999   2   1  NA  NA
``````