What is the range in R and how is it calculated? Can you provide examples?

The range in R refers to the difference between the highest and lowest values in a dataset. It is calculated by subtracting the lowest value from the highest value. For example, if a dataset consists of the numbers 2, 4, 6, 8, and 10, the range would be 10 – 2 = 8. In R, the range can also be calculated using the “range()” function, which returns a vector containing the minimum and maximum values in the dataset. This value is useful for understanding the spread of data and identifying any outliers.

Find the Range in R (With Examples)


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 

RelatedA 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

Additional Resources

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

x