Skip to content
Prev 262884 / 398502 Next

Replacing values without looping

Hi,

If you truly have an array, this is option that should be much faster
than a loop:

index <- which(is.na(dat))
dat[index] <- dat[index - 1]

the only catch is that when there previous value is NA, you may have
to go through the process a few times to get them all.  One way to
automate this would be:

index <- which(is.na(dat))

while (any(index)) {
  dat[index] <- dat[index - 1]
  index <- which(is.na(dat))
}

If your dataset has many adjacent missing values, then it would be
worth it to use a fancier technique that looks for the first previous
nonmissing value.  There could even be a clever way with indexing that
I am missing.

HTH,

Josh
On Thu, Jun 16, 2011 at 5:13 AM, wuffmeister <hvemhva at gmail.com> wrote: