15.1 C
London
Friday, July 5, 2024
HomeRDescriptive Statistics in RHow to Calculate Interquartile Range in R (With Examples)

How to Calculate Interquartile Range in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

The interquartile range represents the difference between the first quartile (the 25th percentile) and the third quartile (the 75th percentile) of a dataset.

In simple terms, it measures the spread of the middle 50% of values.

IQR = Q3 – Q1

We can use the built-in IQR() function to calculate the interquartile range of a set of values in R:

IQR(x)

The following examples show how to use this function in practice.

Example 1: Interquartile Range of a Vector

The following code shows how to calculate the interquartile range of values in a vector:

#define vector
x #calculate interquartile range of values in vector
IQR(x)

[1] 14.5

Example 2: Interquartile Range of a Vector with Missing Values

If your vector has missing values, be sure to specify na.rm=TRUE to ignore missing values when calculating the interquartile range:

#define vector with some missing values
x #calculate interquartile range of values in vector
IQR(x, na.rm=TRUE)

[1] 10.25

Example 3: Interquartile Range of Column in Data Frame

The following code shows how to calculate the interquartile range of a specific column in a data frame:

#define data frame
df frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#calculate interquartile range of 'var1' column
IQR(df$var1)

[1] 1

Example 4: Interquartile Range of Several Columns in Data Frame

The following code shows how to calculate the interquartile range of several columns in a data frame:

#define data frame
df frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#calculate interquartile range of 'var1', 'var2', and 'var4' columns
sapply(df[ , c('var1', 'var2', 'var4')], IQR)

var1 var2 var4 
   1    4    7

Additional Resources

How to Find the Range in R
How to Calculate Standard Deviation in R
How to Interpret Interquartile Range
Interquartile Range vs. Standard Deviation: What’s the Difference?

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories