Filling NA in a vector using values ​​other than NA?

What is a compact / efficient way to populate an NA using a value other than NA? For instance:

test = c( 1 , 2 , NA , NA , 5 , NA , 9 , NA , NA )
expected = c( 1 , 2 , 2 , 2 , 5 , 5 , 9 , 9 , 9 )

Here, all NA values ​​“look back” at the first value other than NA. I am trying to avoid the for loop

+5
source share
1 answer
library(zoo)
na.locf(test)
[1] 1 2 2 2 5 5 9 9 9
+7
source

All Articles