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 
[1] 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 
[1] 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
#[1]  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
#[1]  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)

[1] 999 999 999 999   2   1  NA  NA
Related
Grouping functions (tapply, by, aggregate) and the *apply family
Plotting two variables as lines using ggplot2 on the same graph
Extract every nth element of a vector
Changing column names of a data frame
How to unload a package without restarting R
grep using a character vector with multiple patterns
How do I replace NA values with zeros in an R dataframe?
Test if characters are in a string
How to replace NA values in a table for selected columns
data.table vs dplyr: can one do something well the other can't or does poorly?