I am trying to filter a dataframe based on the column "type" and apply a filter criteria on "Date" if "type" matches. Here is an example:
df <- tibble(type = c("A","A","A","A","B","B","B","B","C","C","C","C"),
Date = ymd(c(20190101,20190105,20190110,20191231,20190530,20190630,20190730,20180630,20190730,20190112,20191230,20181215)))
A_date <- c(ymd(2019-01-05),ymd(2019-12-31))
B_date <- c(ymd(2019-05-30),ymd(2019-07-30))
C_date <- c(ymd(2019-01-01),ymd(2019-12-15))
df
# A tibble: 12 x 2
type Date
<chr> <date>
1 A 2019-01-01
2 A 2019-01-05
3 A 2019-01-10
4 A 2019-12-31
5 B 2019-05-30
6 B 2019-06-30
7 B 2019-07-30
8 B 2018-06-30
9 C 2019-07-30
10 C 2019-01-12
11 C 2019-12-30
12 C 2018-12-15
I want to apply a filter such that if type is "A", then filter for all rows with type "A" with Date between A_date, and do the same for "B" and "C". Such that the resulting dataframe would be:
# A tibble: 8 x 2
type Date
<chr> <date>
1 A 2019-01-05
2 A 2019-01-10
3 A 2019-12-31
4 B 2019-05-30
5 B 2019-06-30
6 B 2019-07-30
7 C 2019-07-30
8 C 2019-01-12
Is it possible to do this with tidyverse's "filter_if"? If not, is there any other solutions? Thanks a lot!
Aucun commentaire:
Enregistrer un commentaire