Home > Enterprise >  Select data based on a day in a month, "If date is lesser than a day in a month"
Select data based on a day in a month, "If date is lesser than a day in a month"

Time:04-02

I have a dataset with a column date like this :

id date
1 2018-02-13
2 2019-02-28
3 2014-01-23
4 2021-10-28
5 2022-01-23
6 2019-09-28

I want to select data that have a date lesser than 15th February

I tried an ifelse statement to define 15th february for each year in my database but i want to know if there is an easier way to do so !

Here's the result i'm expecting

id date
1 2018-02-13
3 2014-01-23
5 2022-01-23

Thanks in advance

CodePudding user response:

You could use lubridate

library(lubridate)
library(dplyr)

d %>% filter(month(date)<2 | (month(date)==2 & day(date)<=15))

Output:

  id       date
1  1 2018-02-13
2  3 2014-01-23
3  5 2022-01-23

CodePudding user response:

This is a base R option. Using format check if the month/year is between January 1st and February 15th.

df[between(format(df$date, "%m%d"), "0101", "0215"),]

Output

  id       date
1  1 2018-02-13
3  3 2014-01-23
5  5 2022-01-23
  • Related