Convert Values to Range Between Two Points in R (2 Examples)

In this R tutorial you’ll learn how to rescale numeric data to a specific range.

Example Data

set.seed(9873426)                  # Random numeric vector in R
my_x <- rnorm(10)
my_x                               # Show example vector in RStudio
#  [1]  1.39155103 -0.37645116  0.13125429 -0.10452000  0.75198789  0.36461948  0.71728516  0.02688913  1.14031711 -0.72179421

Example 1: Scale Numerical Values to Range Between 0 & 1

install.packages("scales")         # Install & load scales
library("scales")
rescale(my_x)                      # Rescaling data to 0/1 range
#  [1] 1.0000000 0.1634106 0.4036484 0.2920839 0.6973693 0.5140730 0.6809485 0.3542646 0.8811203 0.0000000

Example 2: Scale Numerical Values to Range Between Any Two Points

rescale(my_x, to = c(- 10, 20))    # Rescaling data to different range
#  [1]  20.000000  -5.097681   2.109453  -1.237482  10.921079   5.422189  10.428456   0.627937  16.433608 -10.000000

Related Tutorials

Please find some related tutorials on topics such as extracting data, dplyr, missing data, and variables below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top