I have the following data frame (simplified) with the country variable as a factor and the value variable has missing values:
country value
AUT NA
AUT
A combination of the packages dplyr and imputeTS can do the job.
library(dplyr)
library(imputeTS)
data %>% group_by(country) %>%
mutate(value = na.locf(value, na.remaining="keep"))
With the na.remaining parameter of the na.locf function of imputeTS you have additionally the option to choose, what to do with the trailing NAs.
These are the options:
By choosing "mean" you would for example get a result with 7 for every GER in the specific example.