Tuesday, February 14, 2017

Apply a function to a vector in an accumulative manner (like cumsum)

cum.func <- function(x, func, ...)
{ 
    ## Purpose: Apply a function to a vector in an accumulative manner (like cumsum)
    ## Arguments:
    ##   x: a vector
    ##   func: a function
    ##   ...: passed to "func"
    ## Return: a vector that is the result of:
    ##   c( func(x[1]),  func(x[1:2]),  func(x[1:3]),  func(x[1:4]),  func(x[1:5]), ... )
    ## Author: Feiming Chen, Date: 30 Jan 2017, 14:06
    ## ________________________________________________
    
    N <- length(x)
    y <- rep_len(NA, N)
    for (i in 1:N) y[i] <- func(x[1:i], ...)
    y[is.na(x)] <- NA
    y
}
if (F) {                                # Unit Test
    cum.func(5:1, mean)                 #  c(5.0, 4.5, 4.0, 3.5, 3.0))
    cum.func(c(NA, 5:1, NA), mean, na.rm=T)                 #  c(NA, 5.0, 4.5, 4.0, 3.5, 3.0, NA)
    cum.func(c(NA, 5:1, NA), sd, na.rm=T)        # NA NA 0.70711 1.00000 1.29099 1.58114 NA
}

No comments:

Post a Comment