简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM