Calculate the last n weekdays

I have a function in R that, given n days, returns a list of the last n weekdays. My solution works great, but it seems inelegant, and I was wondering if there are any simple ways to improve it.

WeekdayList <- function(n) {
    Today <- as.Date(Sys.time())
    days <- c(Today)
    i <- 1
    while (length(days) < n) {
        NewDay <- as.Date(Today-i)
        if (!weekdays(NewDay) %in% c("Saturday", "Sunday")) {
            days <- c(days,NewDay)
        }
        i <- i+1
    }
    days
}

WeekdayList(30)
WeekdayList(2)

Excluding holidays would be a nice feature.

+3
source share
2 answers

Vectoring code is required in R. Here is an example:

WeekdayList2 <- function(n) {
  Today <- as.Date(Sys.time())
  dayz <- seq(Today, Today - 2 * n, "-1 days")
  dayz <- dayz[!(weekdays(dayz) %in% c("Saturday", "Sunday"))]
  dayz <- dayz[seq_len(n)]
  return(dayz)
}
identical(WeekdayList2(1000), WeekdayList(1000))
system.time(WeekdayList2(10000))
system.time(WeekdayList(10000))
[1] TRUE
   user  system elapsed 
      0       0       0 
   user  system elapsed 
   4.90    0.00    4.91 

As you can see, although my function creates a vector twice its size (and then deletes the output), it is much faster than using the for loop. My computer can't even run your function using n = 100000(not what you would need so many days ago), but WeekdayList2 runs it almost instantly.

, , , , , .

+6

Rguy.

WeekdayList3 <- function(n) {
    library(timeDate)
    Today <- as.Date(Sys.time())
    dayz <- rev(seq(Today - 2 * n, Today, "days"))
    years <- as.numeric(unique(format(dayz,'%Y')))
    holidays <- as.Date(holidayNYSE(years))
    dayz <- dayz[!(weekdays(dayz) %in% c("Saturday", "Sunday"))]
    dayz <- dayz[!(dayz %in% holidays)]
    dayz <- dayz[1 : n]
    return(dayz)
}

WeekdayList3(100)
+4

All Articles