[英]subset date vector by months R
可能是一件微不足道的任务,但我无法以R
为base
。 给定日期向量
dates=seq(as.Date("1951-01-01"), as.Date("2013-12-31"), by="month")
我只选择每年的April-Sept
:
idx <- dates
month <- function(x)as.numeric(format(x, '%m'))
index <- which(month(idx) %in% c(4,5,6,7,8,9))# April-Sept of each year
如何获得基于index
的期望日期?
这是您要找的东西吗?
dates[month(dates) %in% 4:9]
由于您说的是基数R:
dates=seq(as.Date("1951-01-01"), as.Date("2013-12-31"), by="month")
get_dates_with_months <- function(date_vector, months_vector) {
new_dates <- list()
for(i in 1:length(date_vector)) {
month <- strsplit(as.character(date_vector[i]), '-')[[1]][2]
if(month %in% months_vector) { new_dates[i] <- list(date_vector[[i]]) }
}
res <- Filter(Negate(is.null), new_dates)
return(res)
}
用法:
new_dates <- get_dates_with_months(dates, c('04','05','06','07','08','09'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.