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
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.
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).
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).
Combine all conditions by using OR :|
Like:
test <- test[!(test$Occupation == "Management" & test$AvgMonthSpend > 59.24 ) | !(test$Occupation == "Manual" & test$AvgMonthSpend > 54.28 ),]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With