Skip to content
Prev 303697 / 398502 Next

merging and obtaining the nearest value

And the following, f4,  uses the same algorithm as f2 but codes
it somewhat more efficiently.  It uses the same closestValue()
function.
f4 <- function (A, B)  {
    A$TYPE <- as.factor(A$TYPE)
    uA <- levels(A$TYPE)
    As <- split(A$DATE, A$TYPE)
    Bs <- split(B$Special_Date, factor(B$TYPE, levels = uA))
    closest <- numeric(nrow(A))
    split(closest, A$TYPE) <- mapply(closestValue, As, Bs)
    A$Difference <- A$DATE - closest
    A
}

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com