Remove Row by Multiple Condition

To remove rows of data from a dataframe based on multiple conditional statements. We use square brackets [ ] with the dataframe and put multiple conditional statements along with AND or OR operator inside it. This slices the dataframe and removes all the rows that do not satisfy the given conditions.

Syntax:

df[ conditional-statement & / | conditional-statement ]

where,

  • df: determines the dataframe to be used.
  • conditional-statement: determines the condition for filtering data.

Example:

In this example. all data points where the x variable is less than zero and the y variable is less than 19 are removed.

R




# create sample data
sample_data <- data.frame( x = rnorm(10),
                          y=rnorm(10,20) )
# print data
print("Sample Data:")
sample_data
  
# filter data
new_data = sample_data[sample_data$x > 0 & sample_data$y > 0.4, ]
  
# print data
print("Filtered Data:")
new_data


Output:

Sample Data:
              x        y
1  -1.091923406 21.14056
2   0.870826346 20.83627
3   0.285727039 20.89009
4  -0.224661613 20.04137
5   0.653407459 19.01530
6   0.001760769 18.36436
7  -0.572623161 19.72691
8  -0.092852143 19.58567
9  -0.423781311 19.99482
10 -1.332091619 19.36539
Filtered Data:
            x        y
2 0.870826346 20.83627
3 0.285727039 20.89009
5 0.653407459 19.01530
6 0.001760769 18.36436

How to Conditionally Remove Rows in R DataFrame?

In this article, we will discuss how to conditionally remove rows from a dataframe in the R Programming Language. We need to remove some rows of data from the dataframe conditionally to prepare the data. For that, we use logical conditions on the basis of which data that doesn’t follow the condition is removed. 

Similar Reads

Method 1: Remove Row by Single Condition

To remove rows of data from a dataframe based on a single conditional statement we use square brackets [ ] with the dataframe and put the conditional statement inside it. This slices the dataframe and removes all the rows that do not satisfy the given condition....

Method 2: Remove Row by Multiple Condition

...

Method 3 : Remove Rows by subset() function

To remove rows of data from a dataframe based on multiple conditional statements. We use square brackets [ ] with the dataframe and put multiple conditional statements along with AND or OR operator inside it. This slices the dataframe and removes all the rows that do not satisfy the given conditions....