Created
August 28, 2018 23:30
-
-
Save deanmarchiori/b1006fd56566c41f3a921281dddc7226 to your computer and use it in GitHub Desktop.
Finds the nth weekday of a given month and year
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
nthdayofmonth <- function(year, month, day, nth = 1){ | |
#' Finds the nth weekday of a given month and year | |
#' | |
#' Enter the year or years, month, and weekday along with the nth | |
#' weekday of the month you are interested in. | |
#' | |
#' @param year Character Vector. Year/s of interest | |
#' @param month Character. The numeric month i.e. "11" for November | |
#' @param day Character. The full weekday of interest, will do partial | |
#' matching. | |
#' @param nth numeric. The cardinality of the weekday of interest. eg. | |
#' nth = 2 with day = "Tuesday" mean the 2nd Tuesday of the month. | |
#' | |
#' @return A character vector of dates | |
day <- match.arg(day, c("Sunday", "Monday", "Tuesday", | |
"Wednesday", "Thursday", | |
"Friday", "Saturday")) | |
datestring <- paste(year, month, "01", sep = "-") | |
datestart <- as.Date(datestring) | |
x <- sapply(datestart, function(x){ | |
datevec <- seq(x, by = 1, length.out = nth * 7) | |
match <- datevec[format(datevec, "%A") == day & format(datevec, "%m") == month][nth] | |
}) | |
out <- as.Date(unlist(x), origin = "1970-01-01") | |
return(out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment