Bugzilla – Bug 14384

Problem with NLSstClosestX; and suggested fix

Last modified: 2010-10-01 22:57:12 UTC

I sent this to R-help sometime in 2009, but I guess it wasn't noticed. Problem is demonstrated with this code, intended to find the approximate 'x' at which the 'y' is midway between the left and right asymptotes. This particular data set returns NA, which is a bit silly! -------------- sXY <- structure(list(x = c(0, 24, 27, 48, 51, 72, 75, 96, 99), y = c(4.98227, 6.38021, 6.90309, 7.77815, 7.64345, 7.23045, 7.27875, 7.11394, 6.95424)), .Names = c("x", "y"), row.names = c(NA, 9L), class = c("sortedXyData", "data.frame")) a <- NLSstLfAsymptote(sXY) d <- NLSstRtAsymptote(sXY) NLSstClosestX(sXY, (a+d)/2) ------------------------ I think the problem arises when the target y value is exactly equal to one of the y values in sXY and can be fixed by trapping that situation thus: -------------------- NLSstClosestX.sortedXyData <- function (xy, yval) { deviations <- xy$y - yval if (any(deviations==0)) xy$x[match(0, deviations)] else { # new line inserted if (any(deviations <= 0)) { dev1 <- max(deviations[deviations <= 0]) lim1 <- xy$x[match(dev1, deviations)] if (all(deviations <= 0)) { return(lim1) } } if (any(deviations >= 0)) { dev2 <- min(deviations[deviations >= 0]) lim2 <- xy$x[match(dev2, deviations)] if (all(deviations >= 0)) { return(lim2) } } dev1 <- abs(dev1) dev2 <- abs(dev2) lim1 + (lim2 - lim1) * dev1/(dev1 + dev2) } # new line inserted } -------------------

I get NaN ... division by zero. Changed for R 2.12.0.