Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Dates of a Certain Weekday from a Year in R

Tags:

r

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,
2012_01_09,
2102_01_16,
etc
like image 542
Kyle Brandt Avatar asked Dec 16 '22 04:12

Kyle Brandt


2 Answers

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"
like image 82
Josh O'Brien Avatar answered Jan 02 '23 02:01

Josh O'Brien


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)
like image 31
Kyle Brandt Avatar answered Jan 02 '23 03:01

Kyle Brandt