r - 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)
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.
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. 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),]
It doesn't work: Error in as.Date.numeric(6 - 23) : 'origin' must be supplied
解决方案
您可以构建感兴趣的范围和子集:
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]
选择
按照 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] })))
推荐阅读
- javascript - Vue过滤器功能总是返回5个以上的元素
- java - java.lang.NumberFormatException: null - 无法读取输入类型
- flutter - 未处理的异常:WebSocketException:与“http://10.5.11.88:7777/socketcluster/#”的连接未升级到 websocket
- php - .htaccess 阻止用户访问某个目录,但通过 jquery ajax 使用该目录中的文件
- python - OpenCV 将图像读取为 3 通道图像,而 PIL 将相同图像读取为 1 通道图像
- flutter - Flutter:无法让 SingleChildScrollView 中的容器垂直扩展
- php - HTML 表单到 CSV 并使用 PHP 下载 CSV
- javascript - 从对象内的函数数组中的回调函数访问正确的“this”
- xml - 如何一次获取 DOMDocument.Validate 中的所有验证错误?
- c# - 如何避免由于独特的约束而标记为未更改并稍后修改?