Scale Data to Range Between Two Values in R (4 Examples)

 

On this page you’ll learn how to convert a vector or data frame column to a range between two points in the R programming language.

Table of contents:

Let’s start right away.

 

Example Data

Let’s first construct some example data:

set.seed(9734798)                                       # Create example data
vec <- runif(100, - 5, 10)
head(vec)                                               # First six values of example data
# [1] -3.9083226 -0.6268464  2.0502755 -3.3730427 -4.4736672 -1.7398908

The previous RStudio console output shows that our example data is a random numeric vector ranging from -5 to 10.

 

Example 1: Convert Values to 0/1 Range Using Base R

The following R programming syntax illustrates how to rescale a vector between the values 0 and 1 using the functions of the basic installation of the R programming language (i.e. min and max).

vec_range1 <- (vec - min(vec)) / (max(vec) - min(vec))  # Scale to 0/1
head(vec_range1)                                        # Print head of scaled values
# [1] 0.06560990 0.28846080 0.47026892 0.10196171 0.02721634 0.21287197

Have a look at the previous output of the RStudio console: It shows the first six values of a new data objects called vec_range1. As you can see, all values are larger than/equal to zero and smaller than/equal to 1.

 

Example 2: Creating User-Defined Function to Convert Values to 0/1 Range

The following R programming syntax shows how to manually create a user-defined function that converts values to a range between 0 and 1.

Have a look at the following R code:

fun_range <- function(x) {                              # Create user-defined function
  (x - min(x)) / (max(x) - min(x))
}

After running the previous R code, we have created a new function called fun_range. Let’s apply this function to our example data:

vec_range2 <- fun_range(x = vec)                        # Scale to 0/1
head(vec_range2)                                        # Print head of scaled values
# [1] 0.06560990 0.28846080 0.47026892 0.10196171 0.02721634 0.21287197

As you can see, the output of the previous R code is exactly the same as in Example 1. However, in case you need to standardize your data to a range between 0 and 1 regularly, then a user-defined function might be more efficient in the long-run.

 

Example 3: Convert Values to 0/1 Range Using scales Package

This example explains how to use the scales package to convert numerical values to a certain range. First, we need to install and load the scales package:

install.packages("scales")                              # Install & load scales
library("scales")

Now, we can apply the rescale function of the scales package to normalize our data to a range from 0 to 1:

vec_range3 <- rescale(vec)                              # Scale to 0/1
head(vec_range3)                                        # Print head of scaled values
# [1] 0.06560990 0.28846080 0.47026892 0.10196171 0.02721634 0.21287197

Again, the output is the same as in the previous examples.

However, the scales package provides even more options, and that’s what I’m going to show you in the next example.

 

Example 4: Convert Values to Any Range Between Two Values Using scales Package

The following syntax explains how to use the rescale function of the scales package (that we have installed and loaded in the previous example already) to convert our data to a range between any two points we want.

In this example, we’ll convert our numeric vector to a range between 0 and 5. However, we could use basically any two starting and ending points we want.

Have a look at the R syntax below:

vec_range4 <- rescale(vec, to = c(0, 5))                # Scale to 0/5
head(vec_range4)                                        # Print head of scaled values
# [1] 0.3280495 1.4423040 2.3513446 0.5098085 0.1360817 1.0643599

This time, the output is a numeric vector ranging from 0 to 5.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video instruction, I illustrate the R programming code of this article:

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

In addition, you may read the other R articles on my website.

 

At this point you should know how to rescale numeric data to a specific range in R programming. Note that we could apply a similar code to scale an entire numeric matrix or data frame as well. Let me know in the comments section below, if you have any further questions. Furthermore, please subscribe to my email newsletter for regular updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


10 Comments. Leave new

  • Hello Joachim,

    Can you explain, for beginners, how to download data about bitcoin?

    Thank you in advance,

    Vlad

    Reply
  • Hello Joachim,

    I have been trying to use the rescale function, but it never works with the ‘to’ argument, it seems there is something I’m not doing right, can you please help?

    Reply
    • Hey Yinka,

      Could you share your code?

      Regards,
      Joachim

      Reply
      • library(foreign)
        setwd(“~BSA 2018/UKDA-8606-spss/spss/spss25”)
        BSA<-read.spss("bsa2018_final_ukda.sav",
        to.data.frame=TRUE,max.value.labels=100)
        dim(BSA)
        attach(BSA)

        library(scales)
        BSA$Income<-as.numeric(HHIncD)
        head(BSA$Income)
        BSA$Income<-rescale(BSA$Income)
        BSA$Income.test<-rescale(BSA$Income, to = c(0,10))

        Error in rescale(BSA$Income, to = c(0, 10)) :
        unused argument (to = c(0, 10))

        Reply
        • Thanks for sharing your code. Maybe this is a problem due to other packages you have loaded. Does the following code work for you?

          scales::rescale(BSA$Income, to = c(0,10))

          Regards,
          Joachim

          Reply
  • Hi Joachim,

    I am getting this error when i attempt to rescale using the scales package:

    Error in UseMethod(“rescale”) : no applicable method for ‘rescale’ applied to an object of class “c(‘tbl_df’, ‘tbl’, ‘dataframe’)”

    Reply

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top