I have a large matrix full of NAs. For each row I would like to replace the NAs with zeros but only if the preceding and following values are zero. The number of NAs between zeros can vary so in the small example below NAs rows a.1 and a.1.2 will be replaced but other rows will remain NA
a.1<-c(1,1,1,0,NA,NA,0,1)
a.1.2 <- c(1,1,0,NA,NA,NA,0,0)
a.2<-c(1,0,1,1,NA,NA,0,1)
a.3<-c(1,0,0,0,NA,NA,1,0)
a.4<-c(1,0,0,1,NA,NA,1,0)
a_matrix<-as.matrix(rbind(a.1,a.1.2,a.2,a.3,a.4))
We can do it with a custom function:
my_func <- function(x) {
r <- rle(is.na(x))
vals <- r$values
lengths <- r$lengths
for (i in 2:(length(vals) - 1)) {
if (vals[i] & !vals[i-1] & !vals[i+1] & x[sum(lengths[1:(i-1)])] == 0 & x[sum(lengths[1:i]) + 1] == 0) {
x[(sum(lengths[1:(i-1)])+1):(sum(lengths[1:i]))] <- 0
}
}
return(x)
}
t(apply(a_matrix, 1, my_func))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
a.1 1 1 1 0 0 0 0 1
a.1.2 1 1 0 0 0 0 0 0
a.2 1 0 1 1 NA NA 0 1
a.3 1 0 0 0 NA NA 1 0
a.4 1 0 0 1 NA NA 1 0
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