[R] Coalesce function in BBmisc, emoa, and microbenchmark packages

R. Michael Weylandt michael.weylandt at gmail.com
Tue Mar 20 14:05:13 CET 2012


The key is that "Reduce" function -- it takes in a list of elements
and combines them iteratively, e.g., `+` is only defined for two
elements (at a time) but we can do something like

Reduce(`+`, list(1,2,3)) = Reduce(`+`, list(1+2,3)) = Reduce(`+`,
list(3,3)) = 3 + 3 = 6

Michael



On Tue, Mar 20, 2012 at 8:51 AM, Paul Miller <pjmiller_57 at yahoo.com> wrote:
> Hi Brian,
>
> This works very well. Still trying to develop some skill with R. So can't say I understand your function completely as yet, but will work on it. I had thought that your function might only work for two columns (because of the "function(x,y)" part), but the example below suggests it will work for any number of columns.
>
> Appreciate your showing this to me.
>
> Thanks,
>
> Paul
>
>
> Demog <- data.frame(PFS = as.Date(c("2006-07-22", NA, "2007-12-16", "2008-01-19", "2009-05-05", "2006-04-29", "2006-06-18", NA)),
>                          DOD = as.Date(c("2006-07-23", "2008-07-09", "2007-12-16", "2008-01-19", "2009-05-05", "2006-04-29", "2006-06-18", NA)),
>                    LKDA = as.Date(c(NA, NA, NA, NA, NA, NA, NA, "2008-03-25")))
>
> coalesce <- function(...) {
>     dots <- list(...)
>     ret <- Reduce(function (x,y) ifelse(!is.na(x),x,y), dots)
>     class(ret) <- class(dots[[1]])
>     ret
> }
>
> Demog$Test <- with(Demog, coalesce(PFS, DOD, LKDA))
>
> ______________________________________________
> 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.



More information about the R-help mailing list