我有[1,10]
c(1,2,9,10)
我希望将其映射到不同的范围,例如[12,102]
c(12,22,92,102)
是否有一个功能已在R中执行此操作?
答案 0 :(得分:16)
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))
使用包scales
。也可以按照@flodel建议的聪明方式利用approxfun
:
linMap <- function(x, a, b) approxfun(range(x), c(a, b))(x)