code123
code123

Reputation: 2146

subset date vector by months R

Probably a trivial task but I cannot get my head around it with base R. Given a date vector like

dates=seq(as.Date("1951-01-01"), as.Date("2013-12-31"), by="month")

I want to select only April-Sept of each year:

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

How can I get the desired date based on index?

Upvotes: 1

Views: 295

Answers (2)

Cybernetic
Cybernetic

Reputation: 13334

Since you said base 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)
}

Usage:

new_dates <- get_dates_with_months(dates, c('04','05','06','07','08','09'))

Upvotes: 1

LucyMLi
LucyMLi

Reputation: 657

Is this what you're looking for?

dates[month(dates) %in% 4:9]

Upvotes: 1

Related Questions