I have a vector in the range [1,10]
c(1,2,9,10)
and I want to map it to a different range, for example [12,102]
c(12,22,92,102)
Is there a function that already does this in R?
Join Stack Overflow to learn, share knowledge, and build your career.
I have a vector in the range [1,10]
c(1,2,9,10)
and I want to map it to a different range, for example [12,102]
c(12,22,92,102)
Is there a function that already does this in R?
linMap <- function(x, from, to)
(x - min(x)) / max(x - min(x)) * (to - from) + from
linMap(vec, 12, 102)
# [1] 12 22 92 102
Or more explicitly:
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))
works using the package scales
. Also one could exploit approxfun
in a clever way as suggested by @flodel:
linMap <- function(x, a, b) approxfun(range(x), c(a, b))(x)
linMap
and rescale
where the some columns go to zero in R 3.3.2. Example values all.dat <- c(2274959, 1531001)
. Do you know why?
– Léo Léopold Hertz 준영
Nov 22 '16 at 16:53
all.dat
is x
in my answer's notation. Then what is from
, to
, your expected output and what you are getting instead?
– Julius Vainora
Nov 22 '16 at 17:02
R
question. It's a question concerning basic linear algebra. – Carl Witthoft Aug 19 '13 at 11:26