[R] Replacing values without looping

Joshua Wiley jwiley.psych at gmail.com
Thu Jun 16 19:25:35 CEST 2011


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:
> I got an array similar to the one below, and want to replace all NAs with the
> previous value.
> 99 8.2 b
> NA 8.3 x
> NA 7.9 x
> 98 8.1 b
> NA 7.7 x
> 99 9.3 b
> ...
>
> i.e. the first two NAs should be replaced to 99, whereas the last one should
> be 98.
>
> I would like to apply a function to reach row, checking if the value in col
> 1 is NA, and if it is, set the value to the previous row's col 1 value.
>
> Haven't been able to do this without looping, which gets very slow for large
> datasets...
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Replacing-values-without-looping-tp3602247p3602247.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list