[R] Conditionally adding a constant

Joshua Wiley jwiley.psych at gmail.com
Mon Jan 2 19:59:53 CET 2012


Here is another approach.  Probably with some thought and fingerwork,
rle() could be used to avoid the while loop, but that should only slow
things down if there are long runs of NAs --- there can be a lot of
NAs as long as they are spaced apart and it should still be quite
efficient.

f <- function(x, y) {
  i <- which(x > 3)
  cond <- TRUE
  while (cond) {
    y[i] <- y[i - 1] + 2L
    cond <- any(is.na(y))
  }
  return(y)
}

df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))

df$y <- f(df$x, df$y)

Cheers,

Josh

On Mon, Jan 2, 2012 at 4:47 AM, Rui Barradas <ruipbarradas at sapo.pt> wrote:
> Hello,
>
> I believe this works.
>
> f1 <- function(x){
>        for(i in 2:length(x)) x[i] <- ifelse(x[i-1] > 3, x[i-1] + 2, x[i])
>        x
> }
>
> f2 <- function(x){
>        for(i in 2:length(x)) x[i] <- ifelse(is.na(x[i]) & (x[i-1] > 3), x[i-1] +
> 2, x[i])
>        x
> }
>
> df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))
>
> apply(df, 2, f1)      # df$x[4] > 3, df$x[5] also changes
> apply(df, 2, f2)      # only df$y has NA's
>
> Maybe there's a better way, avoiding the loop.
>
> Rui Barradas
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Conditionally-adding-a-constant-tp4253049p4253125.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
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list