Skip to content

Instantly share code, notes, and snippets.

@davidtedfordholt
Created June 17, 2021 13:12
Show Gist options
  • Save davidtedfordholt/42e9c954746aafd3f20a789d08937987 to your computer and use it in GitHub Desktop.
Save davidtedfordholt/42e9c954746aafd3f20a789d08937987 to your computer and use it in GitHub Desktop.
small R function to rescale variables
#' Scale a Variable Between a Given Min and Max
#'
#' @param x values to be scaled
#' @param new_min new minimum value
#' @param new_max new maximum value
#'
#' @return an object of the same class as `x`
#' @export
#'
#' @examples
#' x <- runif(100, -100, 100)
#' scale_between(x, 0, 2)
scale_between <-
function(x, new_min = 0, new_max = 1) {
rng <- range(x)
(new_max - new_min) / (rng[2] - rng[1]) * (x - rng[2]) + new_max
}
@davidtedfordholt
Copy link
Author

I totally understand that scales::rescale() exists! I just forget about it, and sometimes I just like using functions that are mine and that read the way my brain works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment