Here's a logic based function in this related Q & A :
rescale <- function(x, from, to) {
maxx <- max(x)
minx <- min(x)
out <- (to - from) * (x - minx)
out <- out / (maxx - minx)
out + from
}
> rescale(1:10, 2, 5)
[1] 2.000000 2.333333 2.666667 3.000000 3.333333 3.666667 4.000000 4.333333
[9] 4.666667 5.000000
Note that this will not work if min(x) == max(x), as we would then divide by 0 in the next line of the last function.
source
share