Skip to content

Instantly share code, notes, and snippets.

@emhart
Last active August 29, 2015 14:12
Show Gist options
  • Save emhart/98fd750b4c400938ce02 to your computer and use it in GitHub Desktop.
Save emhart/98fd750b4c400938ce02 to your computer and use it in GitHub Desktop.
Code to answer @LeahAWasser's question as follows: "Let's say I have an array of numbers. I can adjust the entire array of numbers to fall within a range of 0-1 with the same spread using the equation: (ValueInArray-minvalueArray) / (MaxValueArray - MinVallueArray) Where: ValueInArray = Nth value in the array (calculation performed for each valu…
#' @description Rescale a vector of numbers to an arbitrary range.
#' @param minVal The minimum value in the range to rescale your numbers to
#' @param maxVal The maximum value on the range to rescale your numbers to
#' @param vec The vector you want to rescale
#' @example /dontrun{
#' orig <- runif(10,1,30)
#' rescaled <- arb_rescale(2,5,orig)
#' cbind(orig,rescaled)
#' }
arb_rescale <- function(minVal,maxVal, vec){
## First rescale to 0 and 1
zerOne <- (vec-min(vec))/(max(vec)-min(vec))
### Rescale back to arbitrary size
rescaled <- (zerOne*(maxVal-minVal))+minVal
return(rescaled)
}
## Draw random numebrs
orig <- runif(10,1,30)
## Rescale them
rescaled <- arb_rescale(2,5,orig)
## Now check that you get back your original numbers
goback <- arb_rescale(min(orig),max(orig),rescaled)
## Now original and goback should be the same
cbind(orig,rescaled,goback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment