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
If speed is a consideration then this unstack
/stack
solution is about 4 to 6 times faster than the others on my system although it does entail a slightly longer line of code:
stack(lapply(unstack(data, value ~ country), na.locf, na.rm = FALSE))
Another approach is:
transform(data, value = ave(value, country, FUN = na.locf0))