How to Find the Range in R (With Examples)

The range in R is the difference between the highest and lowest values of a dataset. To find the range in R, you must first calculate the minimum value using the min() function, and the maximum value using the max() function. Then you can subtract the minimum from the maximum to get the range. Examples of how to use these functions to calculate the range in R are provided in the article.


The range is the difference between the largest and the smallest value in a dataset.

We can use the following syntax to find the range of a dataset in R:

data <- c(1, 3, NA, 5, 16, 18, 22, 25, 29)

#calculate range
max(data, na.rm=TRUE) - min(data, na.rm=TRUE)

[1] 28

And we can use the range() function in base R to display the smallest and largest values in the dataset:

data <- c(1, 3, NA, 5, 16, 18, 22, 25, 29)

#calculate range values
range(data, na.rm=TRUE)

[1] 1 29

This tutorial shows several examples of how to calculate the range of datasets in R.

Related: Measures of Dispersion in Statistics

Example 1: Calculate the Range of a Single Variable

The following code shows how to calculate the range of a single variable in R:

#create data frame
df <- data.frame(x=c(1, 3, NA, 5, 16, 18, 22, 25),
                 y=c(NA, 4, 8, 9, 14, 23, 29, 31),
                 z=c(2, NA, 9, 4, 13, 17, 22, 24))

#find range of variable x in the data frame
max(df$x, na.rm=TRUE) - min(df$x, na.rm=TRUE)

[1] 24

Example 2: Calculate the Range of Multiple Variables

The following code shows how to calculate the range of multiple variables in R:

#create data frame
df <- data.frame(x=c(1, 3, NA, 5, 16, 18, 22, 25),
                 y=c(NA, 4, 8, 9, 14, 23, 29, 31),
                 z=c(2, NA, 9, 4, 13, 17, 22, 24))

#find range of variable x and y in the data frame
sapply(df[c('x','y')], function(df) max(df, na.rm=TRUE) - min(df, na.rm=TRUE))

 x  y 
24 27 

#find range of all variables in the data frame
sapply(df, function(df) max(df, na.rm=TRUE) - min(df, na.rm=TRUE))

 x  y  z 
24 27 22 

Related A Guide to apply(), lapply(), sapply(), and tapply() in R

Example 3: Calculate the Range of Entire Data Frame

The following code shows how to calculate the range of all values in a data frame:

#create data frame
df <- data.frame(x=c(1, 3, NA, 5, 16, 18, 22, 25),
                 y=c(NA, 4, 8, 9, 14, 23, 29, 31),
                 z=c(2, NA, 9, 4, 13, 17, 22, 24))

#find range of all values in entire data frame
max(df, na.rm=TRUE) - min(df, na.rm=TRUE)

[1] 30

The following tutorials explain how to perform other common tasks in R:

x