1

Given a vector such as (say) c(2,NA,5,NA,NA,1,NA) the problem is to "last observation carry forward" resulting in vector c(2,2,5,5,5,1,1).

As answered here, na.locf from the zoo package can do this. However, given the simplicity of the problem, and the fact that this is to be performed many times from a "blank" R environment, I would like to do this without loading packages. Is there a way to do it simply and quickly using just basic R? (The vector may be long and may contain many consecutive NAs.)

Community
  • 1
  • 1
Museful
  • 6,711
  • 5
  • 42
  • 68
  • 3
    Check this http://stackoverflow.com/a/1783275/172261 – rcs Nov 07 '13 at 14:47
  • @Arun If it is the same *question*, then the accepted answer on that page would have been a valid answer here, which it isn't. – Museful Nov 18 '13 at 12:34
  • @AnandaMahto If there exists some (any) answer that is valid to questionA but not to questionB then it stands to reason that questionA != questionB. "How to move a balloon without touching it" is not a duplicate of "How to move a balloon" even if they have some common answers. (My other reason for not deleting this question is that that answer is really hard to find unless you were lucky enough to try the word "propagate", which I wasn't, and I suspect others won't be.) – Museful Nov 18 '13 at 17:53
  • 1
    @tennenrishin, fine. But there's no reason to *reopen*. I don't see anyone voting to *delete* the question, and as such, your question will still serve as a signpost to the other question (or an end to someone's searching, whatever the case may be). – A5C1D2H2I1M1N2O1R2T1 Nov 18 '13 at 17:55
  • @AnandaMahto, okay thanks. But how does one "reopen"? By responding to a comment? (And how does one see whether a question is closed?) – Museful Nov 18 '13 at 18:22

2 Answers2

5

Extracted from zoo::na.locf.default

fillInTheBlanks <- function(S) {
  L <- !is.na(S)
  c(S[L][1], S[L])[cumsum(L)+1]
}

See also here.

Community
  • 1
  • 1
rcs
  • 67,191
  • 22
  • 172
  • 153
1

This is one way using rle:

x <- c(2,NA,5,NA,NA,1,NA) 
x[is.na(x)] <- Inf
x[is.infinite(x)] <- with(rle(x), 
    rep(values[which(is.infinite(values)) - 1], lengths[is.infinite(values)])
)
# [1] 2 2 5 5 5 1 1
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113