From 7d5a067724ffada9aca870ce476d6773516c6f69 Mon Sep 17 00:00:00 2001 From: MMenchero Date: Wed, 9 Oct 2024 15:01:31 -0600 Subject: [PATCH] feat: add vectorized date generation --- R/generate_output_dates.R | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/R/generate_output_dates.R b/R/generate_output_dates.R index 9b38675..23326d2 100644 --- a/R/generate_output_dates.R +++ b/R/generate_output_dates.R @@ -14,18 +14,15 @@ #' dates_df <- .generate_output_dates(df_info, freq, h) #' } #' -.generate_output_dates <- function(df_info, freq, h){ - - new_dates <- vector("list", nrow(df_info)) - r_freq <- .r_frequency(freq) - - for(i in 1:nrow(df_info)){ +.generate_output_dates <- function(df_info, freq, h) { + new_dates <- lapply(1:nrow(df_info), function(i) { start_date <- df_info$dates[i] + r_freq <- .r_frequency(freq) - if(freq %in% c("QE", "Q")){ - dt <- seq(from = start_date, by = r_freq, length.out = h+1) + if (freq %in% c("QE", "Q")) { + # End of quarter dates are: "YYYY-03-31", "YYYY-06-30", "YYYY-09-30", "YYYY-12-31". + dt <- seq(from = start_date, by = "quarter", length.out = h + 1) month <- lubridate::month(start_date) - dt <- seq(from = start_date, by = "quarter", length.out = h+1) # Calendar adjustments if (month %in% c(3, 12)) { @@ -44,21 +41,19 @@ } } } - - }else if(freq %in% c("ME", "M")){ - start_date <- start_date+lubridate::days(1) - dt <- seq(from = start_date, by = r_freq, length.out = h+1)-lubridate::days(1) - }else{ - dt <- seq(df_info$dates[i], by = r_freq, length.out = h+1) + } else if (freq %in% c("ME", "M")) { + dt <- seq(from = start_date + lubridate::days(1), by = r_freq, length.out = h + 1) - lubridate::days(1) + } else { + dt <- seq(from = start_date, by = r_freq, length.out = h + 1) } - new_dates[[i]] <- dt[2:length(dt)] - } + dt[2:length(dt)] + }) dates_df <- data.frame(lapply(new_dates, as.POSIXct)) ids <- df_info$unique_id - if(inherits(df_info$unique_id, "numeric") | inherits(df_info$unique_id, "integer")){ + if (inherits(df_info$unique_id, "numeric") | inherits(df_info$unique_id, "integer")) { ids <- as.character(df_info$unique_id) } names(dates_df) <- ids