Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter dataset by values IF column contains certain string

I have a dataset that looks like this:

> dput(df)
structure(list(Car = c("Mazda", "Mazda", "Mazda", "Mazda", "Mazda", 
"Mazda", "Lexus"), Date = c("2/20/20", "2/21/20", "2/22/20", 
"2/23/20", "2/24/20", "2/25/20", "9/3/20")), class = "data.frame", row.names = c(NA, 
-7L))

I would only like to filter the Dates where the Car=="Mazda".

In this scenerio, I would like to remove the rows for Mazda cars if the date range is not between 2/20/20 – 2/23/20.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you!

>Solution :

You could filter with between from dplyr like this:

library(dplyr)
df %>%
  filter(Car == 'Mazda' & between(Date, '2/20/20', '2/23/20'))
#>     Car    Date
#> 1 Mazda 2/20/20
#> 2 Mazda 2/21/20
#> 3 Mazda 2/22/20
#> 4 Mazda 2/23/20

You could use not ! like this:

library(dplyr)
df %>%
  filter(!(Car == 'Mazda' & !between(Date, '2/20/20', '2/23/20')))
#>     Car    Date
#> 1 Mazda 2/20/20
#> 2 Mazda 2/21/20
#> 3 Mazda 2/22/20
#> 4 Mazda 2/23/20
#> 5 Lexus  9/3/20

Created on 2023-03-23 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading