How to create a linear conversion function in R?

I am trying to make a function that repaints a vector lying between the two arguments lower and upper. And scaling is done by linear transformation.

# rescales x to lie between lower and upper
rescale <- function(x, lower = 0, upper = 1){
slope <- (upper-lower)/(which.max(x)-which.min(x))
intercept <- slope*(x-which.max(x))+upper
y <- intercept + slope * x
return(list(new = y, coef = c(intercept = intercept, slope = slope)))
}

I feel like I'm not on the right track. Please give me some tips to do it right.

+4
source share
1 answer

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.

+2
source

Source: https://habr.com/ru/post/1529119/


All Articles