Skip to content

Instantly share code, notes, and snippets.

@trinker
Last active May 12, 2021 00:19
Show Gist options
  • Save trinker/1f94189513705adf158c9bc1f6c08db8 to your computer and use it in GitHub Desktop.
Save trinker/1f94189513705adf158c9bc1f6c08db8 to your computer and use it in GitHub Desktop.
generalized rescaling
general_rescale <- function(x, lower, upper){
rng <- range(x, na.rm = TRUE, finite = TRUE)
if (diff(rng) == 0) return(stats::setNames(rep(upper, length(x)), names(x)))
(x - rng[1])/diff(rng) * diff(range(c(lower, upper))) + lower
}
x <- c(NA, 1:10)
general_rescale(x, 0, 1)
general_rescale(x, -1, 1)
general_rescale(x, 0, 100)
@trinker
Copy link
Author

trinker commented May 12, 2021

Python Version

def general_rescale(x, lower = .5, upper = 1):

    x = pd.Series(x)
    rng = [x.min(), x.max()] 
    drange = rng[1] - rng[0]
    
    if (drange == 0):
        return x
    
    return ((x - rng[0])/drange) * (upper - lower) + lower


x = [None] + list(range(1,11))
general_rescale(x, .5, 1)

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