na.locf0(x)
will fill in the NA
values with the last occurring value in x
while leaving leading NA
values in place so that its output is the same length as its input; thus, if a position in na.locf(x)
is not NA
but that same position is NA
in x
then na.locf0
would have filled it in. Those positions have the value TRUE in the logical expression shown in the code below so set the values of x
at those positions to "L"
. We use replace
to do that non-destructively (i.e. we output the desired vector without modifying x
itself).
library(zoo)
x <- c(NA, NA, NA, NA, "L", NA, NA, "L", "T", "C") # test data
replace(x, !is.na(na.locf0(x)) & is.na(x), "L")
## [1] NA NA NA NA "L" "L" "L" "L" "T" "C"
Note
If we knew that the NAs to be filled in all follow L
(as in the sample data in the question) then
na.locf0(x)
would be sufficient; however, if the general case is as described in the question then the replace
code above will be needed.
Variation
A variation of the above is to replace all NA
values with "L"
and then in that replace those positions that are NA
in na.locf0(x)
with NA
.
replace(replace(x, is.na(x), "L"), is.na(na.locf0(x)), NA)
## [1] NA NA NA NA "L" "L" "L" "L" "T" "C"