'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
Solution 1:[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
Solution 2:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
| Solution 2 | langtang |
