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

Paul Miller pjmiller_57 at yahoo.com
Tue Mar 20 13:51:58 CET 2012

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. 



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]])

Demog$Test <- with(Demog, coalesce(PFS, DOD, LKDA))

More information about the R-help mailing list