IQR Function in R (2 Examples) | How to Compute the Interquartile Range

 

This article explains how to compute an Interquartile Range (IQR) in the R programming language.

The tutorial is mainly based on the IQR() R function. So let’s have a look at the basic R syntax and the definition of IQR() first:

 

Basic R Syntax of IQR():

IQR(x)

 

Definition of IQR():

The IQR function computes the Interquartile Range of a numeric input vector.

 

In the following article, I’ll explain in two examples how to use the IQR function in R.

Let’s dig in!

 

Example 1: Compute Interquartile Range in R

For the first example, I’m going to use the mtcars data set. The data can be loaded to R as follows:

data(mtcars)
head(mtcars)

 

MTCARS Data

Table 1: The mtcars Data Set in R.

 

Let’s assume that we want to know the IQR of the first column mpg. Then we can use the following R code:

IQR(mtcars$mpg)
# 7.375

As you can see based on the RStudio console output, the IQR of the mpg column is 7.375.

 

Example 2: Handling NA Values with IQR R Function

The occurrence of NA values is a typical problem when the IQR is calculated in R. I’ll show you the problem in practice…

First, let’s create an example vector that contains NAs:

vec <- c(3, 9, 1, 5, 6, 1, NA, 1, NA)

Now, let’s try to compute the IQR of this vector as we did in Example 1:

IQR(vec)
# Error in quantile.default(as.numeric(x), c(0.25, 0.75), na.rm = na.rm

ERROR! We are not able to calculate the IQR while our data contains NAs.

Fortunately, the R programming language provides an easy solution for this problem. We simply have to specify na.rm = TRUE within the IQR command. Let’s do this:

IQR(vec, na.rm = TRUE)
# 4.5

As you can see, the RStudio console now returns the IQR of our example vector (i.e. 4.5).

 

Further Resources

So far, this tutorial explained how to compute the Interquartile Range in R. As you have seen, it’s very easy to use the R programming language as an IQR calculator.

However, if you want to learn more about the theoretical research concept and the statistical interpretation of the IQR rule, you might have a look at the following YouTube video of the Khan Academy:

 

 

Furthermore, you could have a look at the other R tutorials on my website. Some interesting tutorials can be found below:

In summary: I hope you know at this point how to compute and interpret the Interquartile Range. In case you have any comments or questions, don’t hesitate to let me know in the comments section 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.

Menu
Top