简体   繁体   English

Select 数据基于一个月中的某一天,“如果日期小于一个月中的某一天”

[英]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 ID date日期
1 1个 2018-02-13 2018-02-13
2 2个 2019-02-28 2019-02-28
3 3个 2014-01-23 2014-01-23
4 4个 2021-10-28 2021-10-28
5 5个 2022-01-23 2022-01-23
6 6个 2019-09-28 2019-09-28

I want to select data that have a date lesser than 15th February我想要 select 日期小于 2 月 15 日的数据

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 !我尝试使用 ifelse 语句在我的数据库中定义每年的 2 月 15 日,但我想知道是否有更简单的方法!

Here's the result i'm expecting这是我期待的结果

id ID date日期
1 1个 2018-02-13 2018-02-13
3 3个 2014-01-23 2014-01-23
5 5个 2022-01-23 2022-01-23

Thanks in advance提前致谢

You could use lubridate你可以使用lubridate

library(lubridate)
library(dplyr)

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

Output: Output:

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

This is a base R option.这是一个基本的 R 选项。 Using format check if the month/year is between January 1st and February 15th.使用format检查月份/年份是否在 1 月 1 日和 2 月 15 日之间。

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

Output Output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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