propagating data within a vector

Package zoo has a function na.locf():

R> library("zoo")
R> na.locf(c(1, 2, 3, 4))
[1] 1 2 3 4
R> na.locf(c(1, NA, NA, 2, 3, NA, 4))
[1] 1 1 1 2 3 3 4

na.locf: Last Observation Carried Forward; Generic function for replacing each ‘NA’ with the most recent non-‘NA’ prior to it.

See the source code of the function na.locf.default, it doesn't need a for-loop.


I'm doing some minimal copy&paste from the zoo library (thanks again rcs for pointing me at it) and this is what I really needed:

fillInTheBlanks <- function(S) {
  ## NA in S are replaced with observed values

  ## accepts a vector possibly holding NA values and returns a vector
  ## where all observed values are carried forward and the first is
  ## also carried backward.  cfr na.locf from zoo library.
  L <- !is.na(S)
  c(S[L][1], S[L])[cumsum(L)+1]
}