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