Question

I'm trying to perform a piecewise linear transformation of my data. Here's an example table describing a transformation:

dat <- data.frame(x.low = 0:2, x.high = 1:3, y.low=c(0, 2, 3), y.high=c(2, 3, 10))
dat
#   x.low x.high y.low y.high
# 1     0      1     0      2
# 2     1      2     2      3
# 3     2      3     3     10

If I defined x <- c(1.75, 2.5), I would expect transformed values 2.75 and 6.5 (my elements would be matched by rows 2 and 3 of dat, respectively).

I know how to solve this problem with a for loop, iterating through the rows of dat and transforming the corresponding values:

pw.lin.trans <- function(x, m) {
  out <- rep(NA, length(x))
  for (i in seq(nrow(m))) {
    matching <- x >= m$x.low[i] & x <= m$x.high[i]
    out[matching] <- m$y.low[i] + (x[matching] - m$x.low[i]) /
      (m$x.high[i] - m$x.low[i]) * (m$y.high[i] - m$y.low[i])
  }
  out
}
pw.lin.trans(x, dat)
# [1] 2.75 6.50

While this works, it strikes me there should be a better approach that matches x values to rows of dat and then performs all the interpolations in a single computation. Could somebody point me to a non-for-loop solution for this problem?

Was it helpful?

Solution

Try approx:

(xp <- unique(c(dat$x.low, dat$x.high)))
## [1] 0 1 2 3
(yp <- unique(c(dat$y.low, dat$y.high)))
## [1]  0  2  3 10
x <- c(1.75, 2.5)
approx(xp, yp, x)
## $x
## [1] 1.75 2.50
## 
## $y
## [1] 2.75 6.50

or approxfun (which returns a new function):

f <- approxfun(xp, yp)
f(x)
## [1] 2.75 6.50

Some benchmarks:

set.seed(123L)
x <- runif(10000, min(xp), max(yp))
library(microbenchmark)
microbenchmark(
  pw.lin.trans(x, dat),
  approx(xp, yp, x)$y,
  f(x)
)
## Unit: microseconds
##                  expr      min       lq    median        uq      max neval
##  pw.lin.trans(x, dat) 3364.241 3395.244 3614.0375 3641.7365 6170.268   100
##   approx(xp, yp, x)$y  359.080  379.669  424.0895  453.6800  522.756   100
##                  f(x)  202.899  209.168  217.8715  232.3555  293.499   100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top