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.

Syntax:

df[ conditional-statement ]

where,

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

Example:

In this example. all data points where x variable is less than zero 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, ]
  
# print data
print("Filtered Data:")
new_data


Output:

Sample Data:
           x        y
1   1.0356175 19.36691
2  -0.2071733 21.38060
3  -1.3449463 19.56191
4  -0.5313073 19.49135
5   1.7880192 19.52463
6  -0.7151556 19.93802
7   1.5074344 20.82541
8  -1.0754972 20.59427
9  -0.2483219 19.21103
10 -0.8892829 18.93114
Filtered Data:
        x        y
1 1.035617 19.36691
5 1.788019 19.52463
7 1.507434 20.82541
10  1.0460800 20.05319

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