[R] Conditionally adding a constant

jim holtman jholtman at gmail.com
Mon Jan 2 20:43:01 CET 2012


Here is a way of doing it without loops:

> df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))
>
> require(zoo)  # need na.locf to fix the NAs
>
> # replace NA with preceeding values
> df$y <- na.locf(df$y)
> df
  x  y
1 1 10
2 2 20
3 3 30
4 4 30
5 5 30
>
> # assuming that you want to increment the counts when x > 3
> inc <- cumsum(df$x > 3) * 2
> inc
[1] 0 0 0 2 4
>
> df$y <- df$y + inc
> df
  x  y
1 1 10
2 2 20
3 3 30
4 4 32
5 5 34
>
>
>
>


On Mon, Jan 2, 2012 at 1:59 PM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
> 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/
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list