filtering by month-date

Viewed 627

Let's say I have a column like this:

Data
2020-03-25
2020-03-26
2020-03-27
2020-03-28
2020-03-29
2020-03-30
2020-03-31
...
2020-06-31

I want to filter by months March, June, and September, but with only date 31 or 30 if 31 is not available. So at the end I want to have:

Data
2020-03-31
2020-06-30
2020-09-30

I tried

library(lubridate)

filter(data, month(data) == 3 | month(data) == 6 | month(data) == 9)
filter(data, day(data) == 31 | day(data) == 30)

But at the end I get both 31 and 30. How should I either get 31 or 30 if 31 is not available?

1 Answers

You can filter for months 3, 6 and 9 and select the max date in each month which will give you last available date in those months.

library(dplyr)
library(lubridate)

df %>%
  mutate(month = month(Data)) %>%
  filter(month %in% c(3, 6, 9)) %>%
  group_by(month) %>%
  slice(which.max(Data)) -> result

result
Related