6 C
London
Tuesday, March 11, 2025
HomeStatistics TutorialRHow to Remove Outliers from Multiple Columns in R

How to Remove Outliers from Multiple Columns in R

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...

Often you may want to remove outliers from multiple columns at once in R.

One common way to define an observation as an outlier is if it is 1.5 times the interquartile range greater than the third quartile (Q3) or 1.5 times the interquartile range less than the first quartile (Q1).

Using this definition, we can use the following steps to create a simple function to identify outliers and then apply this function across multiple columns in an R data frame.

Step 1: Create data frame.

First, let’s create a data frame in R:

df 

Step 2: Define outlier function.

Next, let’s define a function that can identify outliers and a function that can then remove outliers:

outliers function(x) {

  Q1 probs=.25)
  Q3 probs=.75)
  iqr = Q3-Q1

 upper_limit = Q3 + (iqr*1.5)
 lower_limit = Q1 - (iqr*1.5)

 x > upper_limit | x function(df, cols = names(df)) {
  for (col in cols) {
    df 

Step 3: Apply outlier function to data frame.

Lastly, let’s apply this function across multiple columns of the data frame to remove outliers:

remove_outliers(df, c('var1', 'var2', 'var3'))

  index var1 var2 var3
1     1    4    1    9
2     2    4    2    9
3     3    5    4    9
4     4    4    4    5
5     5    3    6    5
9     9    4    5   11

You can find more R tutorials here.

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