简体   繁体   English

按日和月选择时间段

[英]Select a time period by day and month

I have a dataframe organized by year. 我有一个按年份组织的数据框。 For example: date <- seq(as.Date("2001-07-20"),as.Date("2010-12-31"),by = 1) 例如:date <-seq(as.Date(“ 2001-07-20”),as.Date(“ 2010-12-31”),by = 1)
Now I want to select a subset by using two time periods: June 23 to July 13 AND July 20 to Aug 9 for 2004-2008. 现在,我想使用两个时间段选择一个子集:2004-2008年的6月23日至7月13日以及7月20日至8月9日。 Could you provide some clue? 你能提供一些线索吗? Thanks! 谢谢!

Yes, it can be solved by: test[date %between% c("2004-07-20", "2004-08-09")]... but there are many years in my data, the code can be very repetitive. 是的,可以通过以下方法解决:test [date%between%c(“ 2004-07-20”,“ 2004-08-09”)] ...但是我的数据中有很多年,代码可能非常重复。 I wonder if it can be solved like: 我想知道是否可以像这样解决:

df$md <- format(as.Date(df$date), "%m-%d") df <- df[df$md %in% c(as.Date(06-23):Date(07-13), Date(07-20):Date(08-09)) & year %in% (2004:2008),] df $ md <-format(as.Date(df $ date),“%m-%d”)df <-df [df $ md%in%c(as.Date(06-23):Date(07- 13),日期(07-20):日期(08-09))和年份%in%(2004:2008),]

It doesn't work: Error in as.Date.numeric(6 - 23) : 'origin' must be supplied 它不起作用:as.Date.numeric(6-23)中的错误:必须提供'origin'

You can construct the ranges of interest and subset: 您可以构建兴趣范围和子集:

library(lubridate)    
date <- seq(as.Date("2001-07-20",origin="1970-01-01"),as.Date("2010-12-31",origin="1970-01-01"),by = 1) 

range1 <- as.Date(unlist(lapply(c(0:4),function(y) seq(as.Date("2004-06-23",origin="1970-01-01"),as.Date("2004-07-13",origin="1970-01-01"),by="1 day") + years(y))),origin="1970-01-01")
range2 <- as.Date(unlist(lapply(c(0:4),function(y) seq(as.Date("2004-07-20",origin="1970-01-01"),as.Date("2004-08-09",origin="1970-01-01"),by="1 day") + years(y))),origin="1970-01-01")

date[date %in% range1 | date %in% range2]

Alternative 替代

Alternative answer using %between% as suggested in OP 在OP中使用%between%的替代答案

library(lubridate)
dates <- seq(as.Date("2001-07-20"),as.Date("2010-12-31"),by = 1)

r1 <- c(as.Date("2004-06-23"),as.Date("2004-07-13"))
r2 <- c(as.Date("2004-07-20"),as.Date("2004-08-09"))

ranges <- lapply(c(0:4),function(y) list(r1=r1 + years(y),r2=r2+years(y)))
as.Date(unlist(lapply(ranges,function(r) { dates[dates %between% r$r1 | dates %between% r$r2] })))

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

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