I need to replace the first NAs 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'd be 1).
I have tried multiple methods, such as zoo::na.locf and zoo::na.fill, but they only work for the NAs in the middle of the vector, but not the beginning. Is there a way that I can get around this?
You could 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
I would use cumprod(is.na()) to make an index to the leading NAs; the cumprod will zero out any NAs in the middle or end. You'll also need to convert it back to logical, either with as.logical or double negation.
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
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