How to map a vector to a different range in R?

前端 未结 1 408
误落风尘
误落风尘 2021-02-13 07:19

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]

1条回答
  •  悲哀的现实
    2021-02-13 07:57

    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)
    

    0 讨论(0)
提交回复
热议问题