Get Dates of a Certain Weekday from a Year in R

前端 未结 3 1605
借酒劲吻你
借酒劲吻你 2020-12-06 22:36

How might I generate a list of date objects (POSIXct or lt) for each Monday of a year?

For instance this year would be (In Year, Month, Day):

2012_01_02,
         


        
3条回答
  •  攒了一身酷
    2020-12-06 22:45

    EDIT: On further reflection, here's a cleaner function for doing the same thing:

    getAllMondays <- function(year) {
        days <- as.POSIXlt(paste(year, 1:366, sep="-"), format="%Y-%j")
        Ms <- days[days$wday==1]
        Ms[!is.na(Ms)]  # Needed to remove NA from day 366 in non-leap years
    }
    getAllMondays(2012)
    

    Here's a function that'll perform the more general task of finding the first Monday in an arbitrary year, and then listing it and all of the other Mondays in that year. It uses seq.POSIXt(), and the argument by = "week" (which is also available for seq.Date()).

    getAllMondays <- function(year) {
        day1 <- as.POSIXlt(paste(year, "01-01", sep="-"))
        day365 <- as.POSIXlt(paste(year, "12-31", sep="-"))
    
        # Find the first Monday of year
        week1 <- as.POSIXlt(seq(day1, length.out=7, by="day"))
        monday1 <- week1[week1$wday == 1]
    
        # Return all Mondays in year
        seq(monday1, day365, by="week")
    }
    
    head(getAllMondays(2012))
    # [1] "2012-01-02 PST" "2012-01-09 PST" "2012-01-16 PST" "2012-01-23 PST"
    # [5] "2012-01-30 PST" "2012-02-06 PST"
    

提交回复
热议问题