Get Dates of a Certain Weekday from a Year in R

前端 未结 3 1535
借酒劲吻你
借酒劲吻你 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"
    
    0 讨论(0)
  • 2020-12-06 22:48

    I found seq.Date which is part of base. Not sure if there are caveats to this method but it seems to do what I want:

    x = seq(as.Date("2012/01/02"), as.Date("2013/01/01"), "7 days")
    as.POSIXct(x)
    
    0 讨论(0)
  • 2020-12-06 23:12
    as.Date("2012_01_02", format="%Y_%m_%d") +seq(0,366,by=7)  # 2012 is a leap year.
    

    If you really want them as DateTimes with all the attendant hassles of timezones then you can coerce them with as.POSIXct.

    0 讨论(0)
提交回复
热议问题