r-lib/scales

Rescale formula/calculation

Saadi4469 opened this issue · 4 comments

I would like to know the formula used in rescale. The purpose is to implement the same calculation in MS-Excel.

Thank you

print(scales:::rescale.numeric)
#> function (x, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE), 
#>     ...) 
#> {
#>     if (zero_range(from) || zero_range(to)) {
#>         return(ifelse(is.na(x), NA, mean(to)))
#>     }
#>     (x - from[1])/diff(from) * diff(to) + to[1]
#> }
#> <bytecode: 0x000002261aa1f620>
#> <environment: namespace:scales>

Created on 2023-08-22 with reprex v2.0.2

Or by default from argument:

$\frac{x - min(x)}{max(x) - min(x)} * (end - start) + start$

Where $end$ is to[2] and $start$ is to[1]. With default to argument, simplifies to:

$\frac{x - min(x)}{max(x) - min(x)}$

Awesome, thank you for the quick response :)

What is x in x - min(x)?

Also, can you please provide some additional guidance as to how I should apply the range (rescale(df$var1, to = c(1,10))) in the to argument in MS-Excel version of the formula?

I think I got it so let's if the rescale range is from 1-100 then the calculation for row value in the column will look like:

(column_first_row_value - min_column_value) / (max_column_value - min_column_value) * (100 - 1) + 1

But then now that I think about it the start and end value should be different for each row right?

like based on the above example would the next row value calculated as follows?

(column_second_row_value - min_column_value) / (max_column_value - min_column_value) * (99 - 1) + 1

Closing this. The input arguments are well documented in the code and further questions should be asked at e.g. https://community.rstudio.com/ as the issue tracker is mainly to track bugs and feature requests