1

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

Othmane
  • 33
  • 4
  • Keep it simple. If a simple `ifelse` is working, other ideas might be fast or opitial for big data but may look complicated to other readers of your code or difficult to understand. If you are facing any specific challenge, pls share. Also good if you try yoru method with variety of dates and see if its works consistently. Try `filter from dplyr` and check `lubridate` package for dates. – anuanand Apr 02 '22 at 02:04
  • Thank you ! I tried another method and it seems to work faster ` df[df$date < ISOdate(year(df$date),02,15),] ` – Othmane Apr 02 '22 at 08:42

2 Answers2

2

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
langtang
  • 22,248
  • 1
  • 12
  • 27
1

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
Ben
  • 28,684
  • 5
  • 23
  • 45