14

我在范围内有一个向量[1,10]

c(1,2,9,10)

我想将它映射到不同的范围,例如[12,102]

c(12,22,92,102)

是否有一个函数已经在 R 中执行此操作?

4

1 回答 1

18
linMap <- function(x, from, to)
  (x - min(x)) / max(x - min(x)) * (to - from) + from

linMap(vec, 12, 102)
# [1]  12  22  92 102

或更明确地说:

linMap <- function(x, from, to) {
  # Shifting the vector so that min(x) == 0
  x <- x - min(x)
  # Scaling to the range of [0, 1]
  x <- x / max(x)
  # Scaling to the needed amplitude
  x <- x * (to - from)
  # Shifting to the needed level
  x + from
}

rescale(vec, c(12, 102))使用包工作scalesapproxfun正如@flodel 所建议的那样,人们也可以以一种聪明的方式加以利用:

linMap <- function(x, a, b) approxfun(range(x), c(a, b))(x)
于 2013-08-18T21:01:00.717 回答