na.locf()
in the zoo
package replaces NAs by carrying the last non-NA value forward. (Not only for trailing NAs, but also NAs in the middle of a vector - I assume you don't have those.) By default, it omits leading NAs. You can replace those by a specified value like this:
> library(zoo)
> xx <- c(NA, NA, 1, NA, 2, 3, NA, NA)
> replacement.for.initial.NAs <- -1
> foo <- min(which(!is.na(xx)))
> c(rep(replacement.for.initial.NAs,foo-1),na.locf(xx))
[1] -1 -1 1 1 2 3 3 3
You can loop this over your individuals. There is probably a smarter way involving apply()
and friends to do this process per row or column of your data structure.