R - replace the first NA in the vector

I need to replace the first NA in a vector (for example:) cc = c(NA, NA, 1, 3, 4)

. I want to replace them with the first non-NA value (in this example it would be 1).

I've tried several methods like zoo::na.locf

and zoo::na.fill

, but they only work for NA in the middle of the vector, but not at the beginning. Is there a way I can get around this?

+3


source to share


3 answers


You can try the first

function from dplyr

as below:

d = c(NA, NA, 1, 3, 4)

library(dplyr)
#first non-na value
a <- first(d[!is.na(d)])
#position of the first non-na value
b <- which(!is.na(d))[1]

#replace the first na values with the non-na from above
d[1:(b-1)] <- a

      



Output:

> d
[1] 1 1 1 3 4

      

+3


source


I would use cumprod(is.na())

to make the index the leading NA; cumprod

will zero out any NA in the middle or at the end. You will also need to convert it back to the logic, either by using as.logical

either a double negative.



R>x <- c(NA, NA, 1,3,4)
R>cumprod(is.na(x))
[1] 1 1 0 0 0
R>i <- cumprod(is.na(x))
R>x[!!i] <- x[which.min(i)]
R>x
[1] 1 1 1 3 4

      

+1


source


I suppose NA is always in the lead? But if not, then for completeness:

na.change <- function(vec){
if(sum(!is.na(vec))==0)return(vec)
if(sum(is.na(vec))==0)return(vec)
if(min(which(is.na(vec)))>max(which(!is.na(vec))))return(vec)# only trailing NAs
idx.min <- min(which(is.na(vec)))
idx.max <- min(which(!is.na(vec[idx.min:length(vec)])))-2+idx.min
vec[idx.min:idx.max] <- vec[idx.max+1]
return(vec)
}

      

0


source







All Articles