Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows based on multiple conditions in r [duplicate]

Tags:

r

I want to delete some rows based on two conditions. Here is my code

test <-datasetjoin[!(datasetjoin$Occupation == "Clerical" & datasetjoin$AvgMonthSpend > 58.515 ),]  
test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ),] 
test <- test[!(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),] 
test <- test[!(test$Occupation == "Professional" & test$AvgMonthSpend > 60.08 ),]   
test <- test[!(test$Occupation == "Skilled Manual" & test$AvgMonthSpend > 57.06 ),] 
test <- test[!(test$NumberCarsOwned == "1" & test$YearlyIncome > (81300-51140) * 1.5 + 81300),] 

Is it possible to get the same result in a more elegant way?

Thanks in advance

Occupation MonthlySpend 
Clerical   60           
Management 59           
Clerical   62           
Clerical   58           
Clerical   63              
Management 56
Management 58      

If Occupation = clerical and MonthlySpend > 60 then drop these rows If Occupation = management and MonthlySpend > 57 then drop these rows. At the end I should get this:

Occupation MonthlySpend
Clerical   58
Management 56
like image 413
Mohamed Khafagy Avatar asked Apr 17 '17 05:04

Mohamed Khafagy


People also ask

How do I remove rows from two conditions in R?

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.

How do I remove specific rows in R based on condition?

For example, we can use the subset() function if we want to drop a row based on a condition. If we prefer to work with the Tidyverse package, we can use the filter() function to remove (or select) rows based on values in a column (conditionally, that is, and the same as using subset).

How do I remove rows with NA in R?

To remove all rows having NA, we can use na. omit function. For Example, if we have a data frame called df that contains some NA values then we can remove all rows that contains at least one NA by using the command na. omit(df).


1 Answers

Combine all conditions by using OR :|

Like:

test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ) | !(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),] 
like image 126
Erdem Akkas Avatar answered Sep 29 '22 09:09

Erdem Akkas