繁体   English   中英

子集日期向量,按月R

[英]subset date vector by months R

可能是一件微不足道的任务,但我无法以Rbase 给定日期向量

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.

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