### Example: Combine observed data with rolling sum aggregation Source: https://baselinenowcast.epinowcast.org/reference/combine_obs_with_pred.html Illustrates using `combine_obs_with_pred` with a rolling sum aggregation for reference times. This requires the `zoo` package to be installed. ```R # Example with rolling sum if (requireNamespace("zoo", quietly = TRUE)) { combine_obs_with_pred(pred_counts, reporting_triangle, ref_time_aggregator = function(x) zoo::rollsum(x, k = 2, align = "right") ) } #> Warning: longer object length is not a multiple of shorter object length #> [1] 349 327 355 325 210 225 ``` -------------------------------- ### Install baselinenowcast using remotes Source: https://baselinenowcast.epinowcast.org/ Use the remotes package to install baselinenowcast directly from GitHub. Ensure you have the remotes package installed. ```R remotes::install_github(file.path("epinowcast", "baselinenowcast")) ``` -------------------------------- ### R Example: Generate Point Nowcast and Uncertainty Params Source: https://baselinenowcast.epinowcast.org/reference/sample_prediction.html Demonstrates how to generate a point nowcast and uncertainty parameters from example data using sample_prediction. This example sets up the necessary data structures and calls the function. ```R # Generate point nowcast and uncertainty params from example data data_as_of <- syn_nssp_df[syn_nssp_df$report_date <= "2026-04-01", ] rep_tri <- as_reporting_triangle(data_as_of) |> truncate_to_delay(max_delay = 5) |> tail(n = 10) #> ℹ Using max_delay = 154 from data #> ℹ Truncating from max_delay = 154 to 5. point_nowcast_matrix <- estimate_and_apply_delay(rep_tri, n = 10) reporting_triangle <- apply_reporting_structure(rep_tri) uncertainty_params <- estimate_uncertainty_retro( rep_tri, n_history_delay = 8, n_retrospective_nowcasts = 2 ) nowcast_pred_draw <- sample_prediction( point_nowcast_matrix, reporting_triangle, uncertainty_params ) nowcast_pred_draw #> [,1] #> 0 #> 0 #> 0 #> 0 #> 0 #> 2026-03-28 5 #> 2026-03-29 38 #> 2026-03-30 48 #> 2026-03-31 131 #> 2026-04-01 236 ``` -------------------------------- ### Standard Usage Example Source: https://baselinenowcast.epinowcast.org/reference/apply_delay.html Demonstrates the standard usage of the `apply_delay` function with an example reporting triangle and estimated delay PMF. The output shows the generated point-nowcast matrix. ```R # Example 1: Standard usage with example dataset delay_pmf <- estimate_delay(example_reporting_triangle) point_nowcast_matrix <- apply_delay( reporting_triangle = example_reporting_triangle, delay_pmf = delay_pmf ) print(point_nowcast_matrix) ``` -------------------------------- ### R - Example usage of sample_nowcast Source: https://baselinenowcast.epinowcast.org/reference/sample_nowcast.html This example demonstrates how to use the sample_nowcast function with example data. It first generates a point nowcast matrix and uncertainty parameters, then calls sample_nowcast to produce a nowcast draw. ```R # Generate point nowcast and uncertainty params from example data data_as_of <- syn_nssp_df[syn_nssp_df$report_date <= "2026-04-01", ] rep_tri <- as_reporting_triangle(data_as_of) %>% truncate_to_delay(max_delay = 5) %>% tail(n = 10) #> ℹ Using max_delay = 154 from data #> ℹ Truncating from max_delay = 154 to 5. point_nowcast_matrix <- estimate_and_apply_delay(rep_tri, n = 10) reporting_triangle <- apply_reporting_structure(rep_tri) uncertainty_params <- estimate_uncertainty_retro( rep_tri, n_history_delay = 8, n_retrospective_nowcasts = 2 ) nowcast_draw <- sample_nowcast( point_nowcast_matrix, reporting_triangle, uncertainty_params ) nowcast_draw #> [,1] #> 472 #> 368 #> 534 #> 364 #> 459 #> 2026-03-28 410 #> 2026-03-29 619 #> 2026-03-30 490 #> 2026-03-31 385 #> 2026-04-01 524 ``` -------------------------------- ### Install baselinenowcast Package Source: https://baselinenowcast.epinowcast.org/ Installs the latest released version of the baselinenowcast package from CRAN. ```R install.packages("baselinenowcast") ``` -------------------------------- ### Install Development Version of baselinenowcast Source: https://baselinenowcast.epinowcast.org/ Installs the development version of the baselinenowcast package from GitHub using the pak package. ```R pak::pak(file.path("epinowcast", "baselinenowcast")) ``` -------------------------------- ### Install baselinenowcast from R-universe Source: https://baselinenowcast.epinowcast.org/ Installs the latest version of the baselinenowcast package from the epinowcast R-universe repository. ```R install.packages("baselinenowcast", repos = "https://epinowcast.r-universe.dev") ``` -------------------------------- ### Get Reporting Structure from Example Triangle Source: https://baselinenowcast.epinowcast.org/reference/get_reporting_structure.html Retrieves the reporting structure from a pre-defined example reporting triangle. This structure indicates how the triangle is organized and is used by other functions like `apply_reporting_structure`. ```r structure <- get_reporting_structure(example_reporting_triangle) structure #> [1] 1 0 1 1 ``` -------------------------------- ### Example: Combine observed data with prediction draws Source: https://baselinenowcast.epinowcast.org/reference/combine_obs_with_pred.html Demonstrates the basic usage of `combine_obs_with_pred` with example data. The function combines predicted counts with observed data from a reporting triangle. ```R # Use example data reporting_triangle <- apply_reporting_structure(example_reporting_triangle) pred_counts <- c(10, 20, 30, 40) combine_obs_with_pred(pred_counts, reporting_triangle) #> Warning: longer object length is not a multiple of shorter object length #> 2024-01-01 2024-01-02 2024-01-03 2024-01-04 2024-01-05 2024-01-06 #> 207 162 195 210 145 130 #> 2024-01-07 #> 125 ``` -------------------------------- ### View Example Reporting Triangle Source: https://baselinenowcast.epinowcast.org/reference/example_downward_corr_rt.html Displays the structure and content of the example reporting triangle, highlighting negative values at delay 2. ```r example_downward_corr_rt ``` -------------------------------- ### View Example Reporting Triangle Source: https://baselinenowcast.epinowcast.org/reference/example_reporting_triangle.html Displays the structure and data of the `example_reporting_triangle`. This is useful for understanding the standard format of a reporting triangle. ```r example_reporting_triangle ``` -------------------------------- ### Estimate Delay using Example Reporting Triangle Source: https://baselinenowcast.epinowcast.org/reference/example_reporting_triangle.html Demonstrates how to use the `example_reporting_triangle` with the `estimate_delay` function. Note that this function requires complete rows for accurate delay estimation. ```r # View the example triangle example_reporting_triangle #> Reporting Triangle #> Delays unit: days #> Reference dates: 2024-01-01 to 2024-01-07 #> Max delay: 3 #> Structure: 1, 0, 1, 1 #> #> 0 1 2 3 #> 2024-01-01 100 55 30 12 #> 2024-01-02 70 40 24 8 #> 2024-01-03 80 50 25 10 #> 2024-01-04 100 50 20 NA #> 2024-01-05 90 45 NA NA #> 2024-01-06 110 NA NA NA #> 2024-01-07 95 NA NA NA # Use in nowcasting - requires complete rows for delay estimation estimate_delay(example_reporting_triangle, n = 6) #> 0 1 2 3 #> 0.51800148 0.28185375 0.14151285 0.05863192 ``` -------------------------------- ### Example Usage of fit_by_horizon Source: https://baselinenowcast.epinowcast.org/reference/fit_by_horizon.html Demonstrates how to use the `fit_by_horizon` function with sample observation and prediction matrices. The output represents estimated uncertainty parameters for each horizon. ```r obs <- matrix( c( 5, 6, 2, 1, 4, 2, 8, 4, 2 ), nrow = 3, byrow = TRUE ) pred <- matrix( c( 4.2, 5.2, 1.8, 0.7, 3.5, 3.4, 7.3, 4.1, 1.2 ), nrow = 3, byrow = TRUE ) disp <- fit_by_horizon(obs = obs, pred = pred) disp #> [1] 999.9999 999.9999 999.9999 ``` -------------------------------- ### R Example: Get Draws on the Rolling Sum Source: https://baselinenowcast.epinowcast.org/reference/sample_prediction.html Shows how to use sample_prediction with a custom ref_time_aggregator to get draws on a rolling sum. This requires the 'zoo' package. ```R # Get draws on the rolling sum if (requireNamespace("zoo", quietly = TRUE)) { nowcast_pred_draw_agg <- sample_prediction( point_nowcast_matrix, reporting_triangle, uncertainty_params, ref_time_aggregator = function(x) zoo::rollsum(x, k = 2, align = "right") ) nowcast_pred_draw_agg } #> [,1] #> [1,] 0 #> [2,] 0 #> [3,] 0 #> [4,] 0 #> [5,] 24 #> [6,] 183 #> [7,] 19 #> [8,] 327 #> [9,] 828 ``` -------------------------------- ### Generate Nowcast Predictions with Rolling Sum Source: https://baselinenowcast.epinowcast.org/reference/sample_predictions.html Use `sample_predictions` to generate nowcast predictions. This example applies a rolling sum of k=2 to the predictions, requiring the `zoo` package. Ensure `zoo` is installed and loaded. ```r if (requireNamespace("zoo", quietly = TRUE)) { nowcast_pred_draws_rolling_df <- sample_predictions( point_nowcast_matrix, reporting_triangle, uncertainty_params, draws = 5, ref_time_aggregator = function(x) zoo::rollsum(x, k = 2, align = "right") ) nowcast_pred_draws_rolling_df } ``` -------------------------------- ### Load Required Libraries for Baselinenowcast Source: https://baselinenowcast.epinowcast.org/articles/baselinenowcast.html Load the necessary libraries for using baselinenowcast, epinowcast, ggplot2, dplyr, and tidyr. Ensure these packages are installed before running. ```R knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(baselinenowcast) library(ggplot2) library(dplyr) library(tidyr) ``` -------------------------------- ### Create Animated Nowcast Comparison (Flipbook) Source: https://baselinenowcast.epinowcast.org/articles/evaluation_example.html This snippet creates an animated visualization of nowcasts by plotting all available nowcast dates and then applying 'gganimate' to transition between states based on the 'nowcast_date'. This results in a flipbook-style animation. Ensure 'gganimate' is installed and loaded. ```R p_all_dates <- plot_multiple_nowcasts( data = mult_nowcasts_to_plot, eval_data_full = eval_data_full ) p_anim <- p_all_dates + labs(title = "Nowcast date: {closest_state}") + transition_states(nowcast_date, transition_length = 0, state_length = 1) + ease_aes("linear") knitr::include_graphics(file.path( "..", "man", "figures", "nowcast_flipbook.gif" )) ``` -------------------------------- ### Load Packages for Nowcasting Source: https://baselinenowcast.epinowcast.org/articles/nssp_nowcast.html Loads necessary R packages for data manipulation, date formatting, plotting, and nowcasting. Ensure `baselinenowcast` is installed. ```r knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) # Load packages library(baselinenowcast) library(dplyr) library(tidyr) library(stringr) library(lubridate) library(ggplot2) ``` -------------------------------- ### Example of validating a reporting triangle Source: https://baselinenowcast.epinowcast.org/reference/assert_reporting_triangle.html Demonstrates how to use `assert_reporting_triangle` with an example reporting triangle object. The function returns NULL invisibly if validation passes. ```r # Validate an example reporting triangle assert_reporting_triangle(example_reporting_triangle) #> NULL ``` -------------------------------- ### Example: Create and convert reporting triangle Source: https://baselinenowcast.epinowcast.org/reference/as_reporting_triangle.tbl_pubdate.html Demonstrates creating a reporting triangle from a dataframe, converting it to reviser vintages, and then back to a reporting triangle. The `delays_unit` is inferred during the second conversion. ```R # Create a reporting triangle data_as_of_df <- syn_nssp_df[syn_nssp_df$report_date <= "2026-04-01", ] rep_tri <- as_reporting_triangle(data = data_as_of_df) #> ℹ Using max_delay = 154 from data # Convert to reviser vintages vintages <- as_reviser_vintages(rep_tri) # Convert back to reporting_triangle; `delays_unit` is inferred from the # spacing of the `time` column. rep_tri_2 <- as_reporting_triangle(data = vintages) #> ℹ Using max_delay = 154 from data print(rep_tri_2) #> Reporting Triangle #> Delays unit: days #> Reference dates: 2025-10-25 to 2026-04-01 #> Max delay: 154 #> Structure: 1 #> #> Showing last 10 of 159 rows #> Showing first 10 of 155 columns #> #> 0 1 2 3 4 5 6 7 8 9 #> 2026-03-23 210 131 34 50 35 12 1 25 20 6 #> 2026-03-24 221 96 22 10 13 6 0 5 9 NA #> 2026-03-25 291 129 17 26 42 29 23 25 NA NA #> 2026-03-26 179 96 22 50 9 8 18 NA NA NA #> 2026-03-27 284 40 41 54 28 12 NA NA NA NA #> 2026-03-28 217 78 46 14 39 NA NA NA NA NA #> 2026-03-29 336 161 62 13 NA NA NA NA NA NA #> 2026-03-30 296 53 55 NA NA NA NA NA NA NA #> 2026-03-31 210 108 NA NA NA NA NA NA NA NA #> 2026-04-01 236 NA NA NA NA NA NA NA NA NA #> #> Use print(x, n_rows = NULL, n_cols = NULL) to see all data ``` -------------------------------- ### Convert reporting_triangle to plain matrix Source: https://baselinenowcast.epinowcast.org/reference/as.matrix.reporting_triangle.html This example demonstrates how to convert a `reporting_triangle` object into a plain matrix using the `as.matrix()` function. It also shows how to verify the class of the resulting object. ```R # Convert reporting_triangle to plain matrix plain_mat <- as.matrix(example_downward_corr_rt) class(plain_mat) # "matrix" "array" #> [1] "matrix" "array" ``` -------------------------------- ### Load Required Packages for Nowcasting Evaluation Source: https://baselinenowcast.epinowcast.org/articles/evaluation_example.html Loads necessary R packages for data manipulation, date handling, plotting, and nowcast evaluation. Ensure these packages are installed before running. ```r knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(baselinenowcast) library(lubridate) library(tidyr) library(dplyr) library(glue) library(purrr) library(gganimate) library(ggplot2) library(scoringutils) ``` -------------------------------- ### Calculate Initial Reports by Reference Date Source: https://baselinenowcast.epinowcast.org/articles/modular_workflow.html Groups the observed data by reference date and sums the counts to get the initial number of cases reported for each reference date. This represents the data available as of the nowcast date. ```r initial_reports <- observed_data | group_by(reference_date) | summarise(initial_count = sum(count)) ``` -------------------------------- ### Get last 3 rows of a reporting_triangle Source: https://baselinenowcast.epinowcast.org/reference/tail.reporting_triangle.html This example shows how to use the tail method to extract the last 3 rows from a reporting_triangle object. Ensure you have a reporting_triangle object available, such as 'example_reporting_triangle'. ```r tail(example_reporting_triangle, n = 3) ``` -------------------------------- ### Create and Use Reporting Triangle Source: https://baselinenowcast.epinowcast.org/reference/reporting_triangle-class.html Demonstrates creating a reporting triangle from data and using it with low-level functions for delay estimation and nowcasting. Also shows direct matrix operations and subsetting. ```R # Create a reporting triangle from data data <- syn_nssp_df[syn_nssp_df$report_date <= "2026-04-01", ] rep_tri <- as_reporting_triangle(data = data) #> ℹ Using max_delay = 154 from data # Use with low-level functions filled <- estimate_and_apply_delay(rep_tri) delay_pmf <- estimate_delay(rep_tri) nowcast <- apply_delay(rep_tri, delay_pmf) # Direct matrix operations total_by_date <- rowSums(rep_tri, na.rm = TRUE) total_by_delay <- colSums(rep_tri, na.rm = TRUE) # Subsetting and inspection recent <- tail(rep_tri, n = 10) summary(rep_tri) #> Reporting Triangle Summary #> Dimensions: 159 x 155 #> Reference period: 2025-10-25 to 2026-04-01 #> Max delay: 154 days #> Structure: 1 #> Most recent complete date: 2025-10-29 (442 cases) #> Dates requiring nowcast: 154 (complete: 5) #> Rows with negatives: 0 #> Zeros: 9905 (77.9% of non-NA values) #> Zeros per row summary: #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.0 18.5 63.0 62.3 100.5 145.0 #> #> Mean delay summary (complete rows): #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 3.615 4.298 4.416 4.414 4.679 5.059 #> #> 99% quantile delay (complete rows): #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 22.0 31.0 31.0 33.4 34.0 49.0 ``` -------------------------------- ### Estimate and apply delay using default parameters Source: https://baselinenowcast.epinowcast.org/reference/estimate_and_apply_delay.html Uses the `estimate_and_apply_delay` function with default parameters to generate a point nowcast. This is useful for a quick estimation when no specific delay distribution is known. ```r pt_nowcast_matrix <- estimate_and_apply_delay( reporting_triangle = example_reporting_triangle ) pt_nowcast_matrix ``` -------------------------------- ### More aggressive truncation to 90th percentile Source: https://baselinenowcast.epinowcast.org/reference/truncate_to_quantile.html This example shows a more aggressive truncation of the reporting triangle to the delay at which 90% of cases have been reported. It uses the same initial reporting triangle as the previous example but specifies a lower quantile cutoff. ```r # More aggressive truncation rep_tri_trunc90 <- truncate_to_quantile(rep_tri, p = 0.90) #> ℹ Truncating to 62 based on 90% quantile. #> ℹ Truncating from max_delay = 154 to 62. col(rep_tri_trunc90) #> [1] 63 ``` -------------------------------- ### Truncate reporting triangle to a specific date Source: https://baselinenowcast.epinowcast.org/reference/truncate_to_date.html This example demonstrates how to use `truncate_to_date` to filter a reporting triangle. It first retrieves reference dates from an example triangle, selects a cutoff date, and then applies the truncation. The output shows the reporting triangle as it would appear up to the specified cutoff date. ```r ref_dates <- get_reference_dates(example_reporting_triangle) cutoff <- ref_dates[length(ref_dates) - 1] truncate_to_date(example_reporting_triangle, reference_date = cutoff) ``` -------------------------------- ### Run Nowcasts with Multiple Specifications Source: https://baselinenowcast.epinowcast.org/articles/evaluation_example.html Iterate through different combinations of 'prop_delay' and 'scale_factor' to run nowcasts and evaluate their performance. This uses 'expand.grid' to create parameter combinations and 'pmap_dfr' for parallel mapping. ```r prop_delays <- c(0.5, 0.7) scale_factors <- c(2.2, 2.3) mult_nowcasts_w_metadata <- mutate( mult_nowcasts, prop_delay = prop_delay, scale_factor = scale_factor ) param_grid <- expand.grid( nowcast_date = nowcast_dates, prop_delay = prop_delays, scale_factor = scale_factors, stringsAsFactors = FALSE ) |> filter(!(prop_delay == 0.5 & scale_factor == 2.2)) mult_nowcasts_ms <- pmap_dfr( param_grid, function(nowcast_date, prop_delay, scale_factor) { nowcast <- run_single_nowcast(nowcast_date, prop_delay, scale_factor, data = syn_nssp_df, max_delay = max_delay ) |> mutate( nowcast_date = as.Date(nowcast_date), prop_delay = prop_delay, scale_factor = scale_factor ) return(nowcast) }, .progress = TRUE ) |> bind_rows(mult_nowcasts_w_metadata) ``` -------------------------------- ### sample_predictions Source: https://baselinenowcast.epinowcast.org/reference/sample_predictions.html Get a dataframe of multiple draws of only the predicted elements of the nowcast vector. ```APIDOC ## sample_predictions ### Description Get a dataframe of multiple draws of only the predicted elements of the nowcast vector. ### Usage ```R sample_predictions( point_nowcast_matrix, reporting_triangle, uncertainty_params, draws = 1000, ... ) ``` ### Arguments * **point_nowcast_matrix** - Matrix of point nowcast predictions and observations, with rows representing the reference times and columns representing the delays. * **reporting_triangle** - A reporting_triangle object with rows representing reference times and columns representing delays. Can be a reporting matrix or incomplete reporting matrix. Can also be a ragged reporting triangle, where multiple columns are reported for the same row (e.g., weekly reporting of daily data). * **uncertainty_params** - Vector of uncertainty parameters ordered from horizon 1 to the maximum horizon. Note that these will be reversed internally to match the ordering of the `point_nowcast_matrix` (where a horizon of 1 is the last entry). * **draws** - Integer indicating the number of draws of the predicted nowcast vector to generate. Default is `1000`. * **...** - Additional arguments passed to `sample_prediction`. ### Value Dataframe containing the predicted point nowcast vectors indexed by predicted count (`pred_count`), reference date (`reference_date`), and the draw index (`draw`). Returns predictions for all reference dates in the input `reporting_triangle` (or fewer if using `ref_time_aggregator`). ### See also Probabilistic nowcast generation functions `combine_obs_with_pred()`, `sample_nb()`, `sample_nowcast()`, `sample_nowcasts()`, `sample_prediction()` ``` -------------------------------- ### sample_prediction Source: https://baselinenowcast.epinowcast.org/reference/index.html Get a draw of only the predicted elements of the nowcast vector. Used in probabilistic nowcasting to isolate predictions. ```APIDOC ## sample_prediction() ### Description Get a draw of only the predicted elements of the nowcast vector. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters This function does not explicitly list parameters in the provided documentation. ``` -------------------------------- ### Generate Probabilistic Nowcasts with sample_nowcasts() Source: https://baselinenowcast.epinowcast.org/articles/modular_workflow.html Generates probabilistic nowcasts by sampling from the nowcast distribution and combining draws with observed data. Requires point nowcast matrix, reporting triangle, and uncertainty parameters. ```r nowcast_draws_df <- sample_nowcasts( point_nowcast_matrix, rep_tri, uncertainty_params = disp_params, draws = 100 ) head(nowcast_draws_df) ``` -------------------------------- ### Get Reference Dates Source: https://baselinenowcast.epinowcast.org/reference/get_reference_dates.html This function retrieves a vector of Date objects representing the reference dates from a reporting triangle. ```APIDOC ## get_reference_dates ### Description Get reference dates from reporting_triangle ### Usage ```R get_reference_dates(x) ``` ### Arguments * `x` (reporting_triangle) - A reporting_triangle object ### Value Vector of Date objects ### Examples ```R ref_dates <- get_reference_dates(example_reporting_triangle) head(ref_dates) ``` ``` -------------------------------- ### Set Baselinenowcast Parameters Source: https://baselinenowcast.epinowcast.org/articles/evaluation_example.html Define parameters for a single baselinenowcast specification, including maximum delay, scale factor, and proportion for delay estimation. ```R max_delay <- 25 scale_factor <- 2.2 prop_delay <- 0.5 ``` -------------------------------- ### Get maximum delay from reporting_triangle Source: https://baselinenowcast.epinowcast.org/reference/get_max_delay.html Retrieves the maximum delay from a reporting_triangle object. This is useful for understanding the full extent of delays in the data. ```r max_delay <- get_max_delay(example_reporting_triangle) max_delay ``` -------------------------------- ### Summarize Reporting Triangle Source: https://baselinenowcast.epinowcast.org/articles/baselinenowcast.html Use `summary()` to get an overview of the reporting triangle. This helps in understanding its dimensions, completeness, and delay characteristics. ```r summary(rep_tri_full) ``` -------------------------------- ### Load COVID-19 Data Source: https://baselinenowcast.epinowcast.org/reference/covid19_data.html This snippet shows how to access the covid19_data dataset. No specific setup or imports are required as it's a built-in dataset. ```r covid19_data ``` -------------------------------- ### Display First Two Nowcast Matrices Source: https://baselinenowcast.epinowcast.org/reference/estimate_and_apply_delays.html Displays the first two estimated nowcast matrices from the list generated by `estimate_and_apply_delays`. This allows for a quick inspection of the results. ```r retro_pt_nowcast_mat_list[1:2] ``` -------------------------------- ### Visualize WIS Components Source: https://baselinenowcast.epinowcast.org/articles/evaluation_example.html Use this code to create a stacked bar chart visualizing the components of WIS (overprediction, underprediction, dispersion) for different model specifications. This helps in understanding the contribution of each component to the overall WIS. ```R scores_summary |> pivot_longer(cols = c("overprediction", "underprediction", "dispersion")) |> mutate( name = factor(name, levels = c( "overprediction", "dispersion", "underprediction" ) ), model_name = glue("pd:{prop_delay} sf:{scale_factor}") ) |> ggplot() + geom_bar(aes(x = model_name, y = value, fill = name), stat = "identity", position = "stack" ) + theme_bw() + scale_fill_manual( name = "WIS component", values = c("maroon4", "blue4", "orange4") ) + theme( axis.text.x = element_text( vjust = 1, hjust = 1, angle = 45, size = 11 ) ) + xlab("Model specification") + ylab("WIS") ``` -------------------------------- ### Calculate Initial Reports Source: https://baselinenowcast.epinowcast.org/articles/baselinenowcast.html Calculates the sum of cases for each reference date based on the data available as of the `nowcast_date`. This represents the 'initial reports' before all delays are observed. ```r initial_reports <- observed_data |> group_by(reference_date) | summarise(initial_count = sum(count)) ``` -------------------------------- ### Get last rows of a reporting_triangle Source: https://baselinenowcast.epinowcast.org/reference/tail.reporting_triangle.html Retrieves the last 'n' rows from a reporting_triangle object. This is useful for inspecting the most recent data entries in a triangle. ```APIDOC ## tail.reporting_triangle ### Description Get last rows of a reporting_triangle ### Usage ```R # S3 method for class 'reporting_triangle' tail(x, n = 6L, ...) ``` ### Arguments * `x` (reporting_triangle): A reporting_triangle object. * `n` (integer): Indicating the number of rows to return. Default is 6. * `...` (any): Additional arguments (not currently used). ### Value Last rows as a reporting_triangle. ### Examples ```R # Get last 3 rows tail(example_reporting_triangle, n = 3) ``` ``` -------------------------------- ### Generate Point Nowcast with `baselinenowcast` Source: https://baselinenowcast.epinowcast.org/reference/baselinenowcast.html Use this snippet to generate a single point estimate for the nowcast. Ensure the `example_reporting_triangle` object is available in your environment. ```r nowcast <- baselinenowcast( example_reporting_triangle, output_type = "point" ) #> Warning: 7 reference times available and 9 are specified. #> ℹ All 7 reference times will be used. #> ℹ 0.5 reference times were specified for delay estimation but 0.857 of reference times used for delay estimation. #> ℹ `prop_delay` not identical to the proportion of reference times used for delay estimation due to rounding. nowcast ``` -------------------------------- ### Get maximum delay from reporting_triangle Source: https://baselinenowcast.epinowcast.org/reference/get_max_delay.html This function calculates the maximum delay present in a reporting triangle. It can optionally consider only delays with non-zero observations. ```APIDOC ## get_max_delay(x, non_zero = FALSE) ### Description Get maximum delay from reporting_triangle ### Arguments * `x` (reporting_triangle): A reporting_triangle object. * `non_zero` (logical): If TRUE, returns the maximum delay where at least one observation is non-zero. Default FALSE. ### Value Maximum delay (integer), or -1 if all zero when non_zero = TRUE ### Examples ```R # Get maximum delay from triangle structure max_delay <- get_max_delay(example_reporting_triangle) print(max_delay) # Get maximum delay with non-zero observations max_delay_nz <- get_max_delay(example_reporting_triangle, non_zero = TRUE) print(max_delay_nz) ``` ``` -------------------------------- ### get_delays_unit Source: https://baselinenowcast.epinowcast.org/reference/get_delays_unit.html Gets the unit of delays from a reporting triangle object. This function is useful for understanding the time granularity of the delay data within the triangle. ```APIDOC ## get_delays_unit ### Description Get delays unit from a reporting triangle. ### Usage ``` get_delays_unit(x) ``` ### Arguments * `x` (reporting_triangle) - A reporting_triangle object. ### Value Character string indicating the delays unit. ### Examples ```R delays_unit <- get_delays_unit(example_reporting_triangle) delays_unit ``` ``` -------------------------------- ### Get delays unit from reporting triangle Source: https://baselinenowcast.epinowcast.org/reference/get_delays_unit.html Retrieves the unit of delays from a reporting triangle object. This is useful for understanding the time granularity of the data. ```r delays_unit <- get_delays_unit(example_reporting_triangle) delays_unit #> [1] "days" ``` -------------------------------- ### Prepare Data for Nowcast Visualization Source: https://baselinenowcast.epinowcast.org/articles/modular_workflow.html Selects and reshapes data to create a long format suitable for plotting, distinguishing between initial reports and final observed counts. Ensures unique reference dates. ```r combined_data <- obs_with_nowcast_draws_df | select(reference_date, initial_count, final_count) | distinct() | pivot_longer( cols = c(initial_count, final_count), names_to = "type", values_to = "count" ) | mutate(type = case_when( type == "initial_count" ~ "Initial reports", type == "final_count" ~ "Final observed data" )) ``` -------------------------------- ### Preprocess and Estimate Delay - R Source: https://baselinenowcast.epinowcast.org/reference/estimate_delay.html Demonstrates preprocessing a reporting triangle to handle negative values before estimating the delay distribution. This ensures that negative values are corrected prior to estimation. ```r # Example 3: Preprocess explicitly before estimation if needed preprocessed_triangle <- preprocess_negative_values(example_downward_corr_rt) #> ℹ Negative values detected in reporting triangle and will be corrected delay_pmf_preprocessed <- estimate_delay( reporting_triangle = preprocessed_triangle, n = 5 ) delay_pmf_preprocessed #> 0 1 2 3 #> 0.64346536 0.26957812 0.00000000 0.08695652 ``` -------------------------------- ### .display_triangle_basics Source: https://baselinenowcast.epinowcast.org/reference/dot-display_triangle_basics.html Internal helper to print common triangle metadata used by both print and summary methods. ```APIDOC ## .display_triangle_basics ### Description Internal helper to print common triangle metadata used by both print and summary methods. ### Usage ```R .display_triangle_basics(x, show_dimensions = FALSE) ``` ### Arguments * **x** (reporting_triangle) - A reporting_triangle object. * **show_dimensions** (logical) - Logical. If TRUE, displays dimensions (rows x cols). Default FALSE. ### Value NULL (displays information via cli). ``` -------------------------------- ### estimate_and_apply_delay Source: https://baselinenowcast.epinowcast.org/reference/estimate_and_apply_delay.html Generates a point nowcast by estimating a delay distribution from the reporting triangle and applying it to complete the triangle. If a delay distribution is specified, this will be used to generate the nowcast, otherwise, a delay distribution will be estimated from the `reporting_triangle`. ```APIDOC ## estimate_and_apply_delay ### Description Generates a point nowcast by estimating a delay distribution from the reporting triangle and applying it to complete the triangle. If a delay distribution is specified, this will be used to generate the nowcast, otherwise, a delay distribution will be estimated from the `reporting_triangle`. ### Usage ```R estimate_and_apply_delay( reporting_triangle, n = nrow(reporting_triangle), delay_pmf = NULL, validate = TRUE ) ``` ### Arguments * **reporting_triangle** (A reporting_triangle object) - A reporting_triangle object with rows representing reference times and columns representing delays. Can be a reporting matrix or incomplete reporting matrix. Can also be a ragged reporting triangle, where multiple columns are reported for the same row (e.g., weekly reporting of daily data). * **n** (Integer) - Integer indicating the number of reference times (observations) to be used in the estimate of the reporting delay, always starting from the most recent reporting delay. The default is to use the whole reporting triangle, so `nrow(reporting_triangle)`. * **delay_pmf** (Vector) - Vector of delays assumed to be indexed starting at the first delay column in `reporting_triangle`. Default is `NULL`, which will estimate a delay from the `reporting_triangle`. * **validate** (Logical) - Logical. If TRUE (default), validates the object. Set to FALSE only when called from functions that already validated. ### Value `pt_nowcast_matrix` A `reporting_triangle` object of point nowcasts with the same structure as the input ### See also High-level workflow wrapper functions `allocate_reference_times()`, `estimate_and_apply_delays()`, `estimate_and_apply_uncertainty()`, `estimate_uncertainty_retro()` ### Examples ```R # Estimate and apply delay using default parameters pt_nowcast_matrix <- estimate_and_apply_delay( reporting_triangle = example_reporting_triangle ) pt_nowcast_matrix # Use downward correction example with specific rows for delay estimation pt_nowcast_matrix <- estimate_and_apply_delay( reporting_triangle = example_downward_corr_rt, n = 5 ) pt_nowcast_matrix # Provide a pre-computed delay PMF delay_pmf <- estimate_delay( reporting_triangle = example_reporting_triangle ) pt_nowcast_matrix <- estimate_and_apply_delay( reporting_triangle = example_reporting_triangle, delay_pmf = delay_pmf ) pt_nowcast_matrix ``` ``` -------------------------------- ### Get Median Delay Source: https://baselinenowcast.epinowcast.org/reference/get_quantile_delay.html Calculates the median delay (50th percentile) for each reference date in a reporting triangle. Assumes the reporting_triangle object is already defined. ```r median_delays <- get_quantile_delay(example_reporting_triangle, p = 0.5) median_delays ``` -------------------------------- ### Get Quantile Delay Function Source: https://baselinenowcast.epinowcast.org/reference/get_quantile_delay.html Calculates the quantile delay for each row of a reporting triangle. The `p` argument specifies the quantile, defaulting to 0.99 (99th percentile). ```APIDOC ## get_quantile_delay(x, p = 0.99) ### Description Get quantile delay for each row of reporting_triangle ### Arguments x A reporting_triangle object p Numeric value between 0 and 1 indicating the quantile to compute. For example, p = 0.99 returns the delay at which 99% of cases have been reported. Default is 0.99. ### Value Vector of quantile delays for each reference date (integer). Returns NA for rows with no observations. ### Examples __``` # Get 99th percentile delay for each reference date quantile_delays_99 <- get_quantile_delay(example_reporting_triangle) quantile_delays_99 #> [1] 3 3 3 2 1 0 0 # Get median delay median_delays <- get_quantile_delay(example_reporting_triangle, p = 0.5) median_delays #> [1] 0 1 1 0 0 0 0 ``` ``` -------------------------------- ### Get 99th Percentile Delay Source: https://baselinenowcast.epinowcast.org/reference/get_quantile_delay.html Calculates the delay at which 99% of cases have been reported for each reference date in a reporting triangle. Assumes the reporting_triangle object is already defined. ```r quantile_delays_99 <- get_quantile_delay(example_reporting_triangle) quantile_delays_99 ``` -------------------------------- ### Citation for baselinenowcast package Source: https://baselinenowcast.epinowcast.org/ Provides the recommended citation for the baselinenowcast package in publications, including a BibTeX entry for LaTeX users. ```text To cite baselinenowcast in publications please use the following. Johnson KE, Tang M, Tyszka E, Nemcova B, Wolffram D, Ergas R, Reich NG, Funk S, Mellor J, Bracher J, Abbott S (2025). "Baseline nowcasting methods for handling delays in epidemiological data." _Wellcome Open Research_. doi:10.12688/wellcomeopenres.25027.1 . . A BibTeX entry for LaTeX users is @Article{ title = {Baseline nowcasting methods for handling delays in epidemiological data}, author = {Kaitlyn E. Johnson and Maria Tang and Emily Tyszka and Barbora Nemcova and Daniel Wolffram and Rosa Ergas and Nicholas G. Reich and Sebastian Funk and Jonathon Mellor and Johannes Bracher and Sam Abbott}, year = {2025}, journal = {Wellcome Open Research}, doi = {10.12688/wellcomeopenres.25027.1}, url = {https://wellcomeopenresearch.org/articles/10-614}, } Johnson KE, Tyszka E, Bracher J, Funk S, Abbott S (2025). _baselinenowcast: Methods for baseline nowcasting right-truncated epidemiological data_. . A BibTeX entry for LaTeX users is @Manual{ license = {MIT}, title = {baselinenowcast: Methods for baseline nowcasting right-truncated epidemiological data}, author = {Kaitlyn E. Johnson and Emily Tyszka and Johannes Bracher and Sebastian Funk and Sam Abbott}, year = {2025}, url = {https://github.com/epinowcast/baselinenowcast/}, } ``` -------------------------------- ### Calculate Delay to Diagnosis Update Source: https://baselinenowcast.epinowcast.org/articles/nssp_nowcast.html Adds a new column to the dataframe calculating the delay in days between the patient's visit start time and each diagnosis update. ```r nssp_updates <- syn_nssp_clean |> mutate(arrival_to_update_delay = as.numeric(difftime( time_stamp, C_Visit_Date_Time, units = "days" ))) ``` -------------------------------- ### Prepare Observed Data as of Nowcast Date Source: https://baselinenowcast.epinowcast.org/articles/baselinenowcast.html Filters the target data to include only reports made on or before the `nowcast_date`. This simulates the data available at the time of the nowcast. ```r observed_data <- filter( target_data, report_date <= nowcast_date ) head(observed_data) #> # A tibble: 6 × 6 #> reference_date location age_group delay count report_date #> #> 1 2021-04-06 DE 00+ 0 149 2021-04-06 #> 2 2021-04-06 DE 00+ 1 140 2021-04-07 #> 3 2021-04-06 DE 00+ 2 61 2021-04-08 #> 4 2021-04-06 DE 00+ 3 52 2021-04-09 #> 5 2021-04-06 DE 00+ 4 36 2021-04-10 #> 6 2021-04-06 DE 00+ 5 8 2021-04-11 ``` -------------------------------- ### sample_nowcasts Source: https://baselinenowcast.epinowcast.org/reference/sample_nowcasts.html Generates multiple draws of a nowcast by combining observed and predicted values. ```APIDOC ## sample_nowcasts ### Description Generate multiple draws of a nowcast combining observed and predicted values. ### Usage ```R sample_nowcasts( point_nowcast_matrix, reporting_triangle, uncertainty_params, draws = 1000, ... ) ``` ### Arguments * **point_nowcast_matrix** (Matrix) - Matrix of point nowcast predictions and observations, with rows representing the reference times and columns representing the delays. * **reporting_triangle** (Object) - A reporting_triangle object with rows representing reference times and columns representing delays. Can be a reporting matrix or incomplete reporting matrix. Can also be a ragged reporting triangle, where multiple columns are reported for the same row (e.g., weekly reporting of daily data). * **uncertainty_params** (Vector) - Vector of uncertainty parameters ordered from horizon 1 to the maximum horizon. Note that these will be reversed internally to match the ordering of the `point_nowcast_matrix` (where a horizon of 1 is the last entry). * **draws** (Integer) - Number of draws of the predicted nowcast vector to generate. Default is `1000`. * **...** - Additional arguments passed to `sample_nowcast`. ### Value Dataframe containing information for multiple draws with columns for the reference date (`reference_date`), the predicted counts (`pred_count`), and the draw number (`draw`). Returns predictions for all reference dates in the input `reporting_triangle` (or fewer if using `ref_time_aggregator`). ### See also Probabilistic nowcast generation functions `combine_obs_with_pred()`, `sample_nb()`, `sample_nowcast()`, `sample_prediction()`, `sample_predictions()` ### Examples ```R # Generate point nowcast and uncertainty params from example data data_as_of <- syn_nssp_df[syn_nssp_df$report_date <= "2026-04-01", ] rep_tri <- as_reporting_triangle(data_as_of) |> truncate_to_delay(max_delay = 5) |> tail(n = 10) point_nowcast_matrix <- estimate_and_apply_delay(rep_tri, n = 10) reporting_triangle <- apply_reporting_structure(rep_tri) uncertainty_params <- estimate_uncertainty_retro( rep_tri, n_history_delay = 8, n_retrospective_nowcasts = 2 ) nowcast_draws <- sample_nowcasts( point_nowcast_matrix, reporting_triangle, uncertainty_params, draws = 5 ) nowcast_draws ``` ``` -------------------------------- ### Estimate and Apply Delays for Retrospective Nowcasts Source: https://baselinenowcast.epinowcast.org/articles/modular_workflow.html Generates a list of point nowcast matrices by estimating and applying delays using retrospective reporting triangles. The number of reference times used for delay estimation is specified by 'n'. ```r retro_pt_nowcast_mat_list <- estimate_and_apply_delays( retro_reporting_triangles = retro_rep_tri_list, n = n_history_delay ) ``` -------------------------------- ### Get reference dates from reporting_triangle Source: https://baselinenowcast.epinowcast.org/reference/get_reference_dates.html Use this function to extract a vector of Date objects representing reference dates from a reporting_triangle object. Ensure you have a reporting_triangle object available. ```R ref_dates <- get_reference_dates(example_reporting_triangle) head(ref_dates) ```