20.5 C
London
Monday, June 2, 2025
HomeStatistics TutorialRR: Remove Rows from Data Frame Based on Condition

R: Remove Rows from Data Frame Based on Condition

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

You can use the subset() function to remove rows with certain values in a data frame in R:

#only keep rows where col1 value is less than 10 and col2 value is less than 8
new_df 10 & col28) 

The following examples show how to use this syntax in practice with the following data frame:

#create data frame
df frame(a=c(1, 3, 4, 6, 8, 9),
                 b=c(7, 8, 8, 7, 13, 16),
                 c=c(11, 13, 13, 18, 19, 22),
                 d=c(12, 16, 18, 22, 29, 38))

#view data frame
df

  a  b  c  d
1 1  7 11 12
2 3  8 13 16
3 4  8 13 18
4 6  7 18 22
5 8 13 19 29
6 9 16 22 38

Example 1: Remove Rows Equal to Some Value

The following code shows how to remove all rows where the value in column ‘c’ is equal to 13:

#remove rows where column 'c' is equal to 13
new_df != 13) 

#view updated data frame
new_df

  a  b  c  d
1 1  7 11 12
4 6  7 18 22
5 8 13 19 29
6 9 16 22 38

Example 2: Remove Rows Equal to One of Several Values

The following code shows how to remove all rows where the value in column ‘b’ is equal to 7 or 8:

#remove rows where value in column b is equal to 7 or 8
new_df !(b %in% c(7, 8)))

#view updated data frame
new_df

  a  b  c  d
5 8 13 19 29
6 9 16 22 38

Example 3: Remove Rows Based on Multiple Conditions

The following code shows how to remove all rows where the value in column ‘b’ is equal to 7 or where the value in column ‘d’ is equal to 38:

#remove rows where value in column b is 7 or value in column d is 38
new_df != 7 & d != 38)

#view updated data frame
new_df

  a  b  c  d
2 3  8 13 16
3 4  8 13 18
5 8 13 19 29

Additional Resources

How to Remove Duplicate Rows in R
How to Use %in% Operator in R
How to Recode Values in R

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