diff_roll_sum: A function to calculate a rolling sum of first differences

View source: R/diff_roll_sum.R

diff_roll_sumR Documentation

A function to calculate a rolling sum of first differences

Description

Calculates a rolling sum of first differences on a vector, or optionally and recommended, calculates first differences and rolling sum by day where missing day values are treated as the same as the last observed value.

Usage

diff_roll_sum(x, date_vec = NULL, window = 14)

Arguments

x

a numeric vector

date_vec

date, vector of dates of equal length to x default NULL

window

int, integer indicating rolling sum window length

Examples

## Not run: 
read_scrape_data(all_dates = TRUE, state = "North Carolina") %>%
    group_by(Name, Jurisdiction) %>%
    # calculate values by name and jurisdication for all of state of NC
    mutate(Res.Act.Est = diff_roll_sum(Residents.Confirmed, Date)) %>%
    # filter here only for the example plot
    filter(Name == "NORTH CAROLINA CORRECTIONAL INSTITUTION FOR WOMEN") %>%
    ggplot(aes(
        x = Date, y = Res.Act.Est, color = Name, fill = Name)) +
    geom_line(size = 1.5) +
    geom_area(alpha = .5) +
    theme_behindbars() +
    scale_color_bbdiscrete() +
    scale_fill_bbdiscrete() +
    theme(legend.position = "none") +
    labs(y = "Estimated Active Cases") +
    ggtitle("Monitoring Facility Outbreaks")

## End(Not run)

# example of difference using position vs using dates for rolling sum diffs
x <- c(1, 1, 4, 4, 7, 9)
sd <- Sys.Date()
date_x <- sd - c(10, 9, 8, 6, 4, 2)

diff_roll_sum(x, window = 2)
## Not run: 
# returns a warning
diff_roll_sum(x, date_x, window = 2)

## End(Not run)


uclalawcovid19behindbars/behindbarstools documentation built on April 22, 2022, 4:08 a.m.