Created
June 17, 2021 13:12
-
-
Save davidtedfordholt/42e9c954746aafd3f20a789d08937987 to your computer and use it in GitHub Desktop.
small R function to rescale variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.