### Install and Load CausalImpact Package Source: https://github.com/google/causalimpact/blob/master/README.md Installs the CausalImpact package from CRAN and loads it into the R session. This is the first step before using any of its functionalities. ```r install.packages("CausalImpact") library(CausalImpact) ``` -------------------------------- ### Perform Causal Impact Analysis with Date-Based Time Series Source: https://context7.com/google/causalimpact/llms.txt This example demonstrates using date-indexed zoo objects for causal impact analysis, which is useful for real-world data. The package automatically formats plots with dates and allows period specification using actual dates. ```r library(CausalImpact) library(zoo) # Create example data with dates set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 # Create date-indexed zoo object time.points <- seq.Date(as.Date("2014-01-01"), by = 1, length.out = 100) data <- zoo(cbind(y, x1), time.points) # Specify periods using dates pre.period <- as.Date(c("2014-01-01", "2014-03-11")) post.period <- as.Date(c("2014-03-12", "2014-04-10")) # Run analysis impact <- CausalImpact(data, pre.period, post.period) # The model stores period information in date format print(impact$model$pre.period) # [1] "2014-01-01" "2014-03-11" print(impact$model$post.period) # [1] "2014-03-12" "2014-04-10" ``` -------------------------------- ### Integrate Custom bsts Model into CausalImpact Source: https://context7.com/google/causalimpact/llms.txt Pass a pre-fitted bsts model to CausalImpact for advanced state space configuration. Ensure the post-period response is set to NA in the input data. ```r library(CausalImpact) library(bsts) # Create data set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 52) y <- 1.2 * x1 + rnorm(52) y[41:52] <- y[41:52] + 10 pre.period <- c(1, 40) post.period <- c(41, 52) # Store actual post-period response before setting to NA post.period.response <- y[post.period[1]:post.period[2]] # Set post-period response to NA (required for bsts model) y[post.period[1]:post.period[2]] <- NA # Build custom bsts model with local level state component ss <- AddLocalLevel(list(), y) # Fit the model (use ping = 0 to suppress iteration output) bsts.model <- bsts(y ~ x1, ss, niter = 1000, ping = 0) # Pass the fitted model to CausalImpact impact <- CausalImpact(bsts.model = bsts.model, post.period.response = post.period.response) # Results can be used normally summary(impact) plot(impact) ``` -------------------------------- ### Generate Numerical Summary Statistics Source: https://context7.com/google/causalimpact/llms.txt Produce a table of actual vs. predicted values and effects, or access the raw summary data frame. ```r library(CausalImpact) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) impact <- CausalImpact(data, c(1, 70), c(71, 100)) # Print summary table summary(impact) # Output: # Posterior inference {CausalImpact} # # Average Cumulative # Actual 99 2982 # Prediction (s.d.) 89 (0.31) 2665 (9.3) # 95% CI [88, 89] [2647, 2683] # # Absolute effect (s.d.) 11 (0.31) 317 (9.3) # 95% CI [9.9, 11] [299, 335] # # Relative effect (s.d.) 12% (0.35%) 12% (0.35%) # 95% CI [11%, 13%] [11%, 13%] # # Posterior tail-area probability p: 0.001 # Posterior probability of an effect: 99.9% # Access raw summary data for custom processing impact$summary # Returns data frame with columns: Actual, Pred, Pred.lower, Pred.upper, Pred.sd, # AbsEffect, AbsEffect.lower, AbsEffect.upper, AbsEffect.sd, # RelEffect, RelEffect.lower, RelEffect.upper, RelEffect.sd, p # Control decimal precision summary(impact, digits = 4) ``` -------------------------------- ### Customize Causal Impact Model with model.args Source: https://context7.com/google/causalimpact/llms.txt Fine-tune the underlying Bayesian structural time-series model using the `model.args` parameter. This allows control over MCMC iterations, seasonality, prior specifications, and regression dynamics. Adjust `nseasons` and `season.duration` for different seasonal patterns. ```r library(CausalImpact) # Create data set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) pre.period <- c(1, 70) post.period <- c(71, 100) # Run analysis with custom model parameters impact <- CausalImpact(data, pre.period, post.period, model.args = list( niter = 5000, # Number of MCMC samples (default: 1000) standardize.data = TRUE, # Standardize data before fitting (default: TRUE) prior.level.sd = 0.01, # Prior SD for local level (default: 0.01) nseasons = 1, # Seasonal period (default: 1, no seasonality) season.duration = 1, # Duration of each season (default: 1) dynamic.regression = FALSE # Time-varying coefficients (default: FALSE) ) ) # For weekly seasonality with daily data: # model.args = list(nseasons = 7, season.duration = 1) # For weekly seasonality with hourly data: # model.args = list(nseasons = 7, season.duration = 24) # For volatile data, use larger prior.level.sd: # model.args = list(prior.level.sd = 0.1) ``` -------------------------------- ### Generate Verbal Interpretation Report Source: https://context7.com/google/causalimpact/llms.txt Produce a plain-language summary of the analysis findings or access the full report text directly. ```r library(CausalImpact) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) impact <- CausalImpact(data, c(1, 70), c(71, 100)) # Print verbal report summary(impact, "report") # Output: # Analysis report {CausalImpact} # # During the post-intervention period, the response variable had an average # value of approx. 99. By contrast, in the absence of an intervention, we # would have expected an average response of 89. The 95% interval of this # counterfactual prediction is [88, 89]. Subtracting this prediction from # the observed response yields an estimate of the causal effect the # intervention had on the response variable. This effect is 11 with a 95% # interval of [9.9, 11]. For a discussion of the significance of this # effect, see below. # # Summing up the individual data points during the post-intervention period # ... [continues with cumulative effects and statistical significance] # The full report text is also stored in the object cat(impact$report) ``` -------------------------------- ### Examine Predictor Inclusion Probabilities Source: https://context7.com/google/causalimpact/llms.txt Analyze variable influence by inspecting posterior inclusion probabilities from the underlying bsts model. Access the bsts model directly for advanced diagnostics. ```r library(CausalImpact) library(bsts) # Create data with multiple predictors set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) x2 <- 50 + arima.sim(model = list(ar = 0.9), n = 100) x3 <- rnorm(100) # Noise predictor y <- 1.2 * x1 + 0.5 * x2 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1, x2, x3) impact <- CausalImpact(data, c(1, 70), c(71, 100)) # Plot predictor inclusion probabilities # Bar height shows probability of inclusion in model # Shading indicates direction (white = negative, black = positive) plot(impact$model$bsts.model, "coefficients") # Access the bsts model directly for more diagnostics bsts.model <- impact$model$bsts.model print(names(bsts.model)) # View posterior samples posterior.samples <- impact$model$posterior.samples dim(posterior.samples) # Returns [n_samples x n_observations] matrix ``` -------------------------------- ### Configure CausalImpact with Custom Confidence Level Source: https://context7.com/google/causalimpact/llms.txt Adjust the alpha parameter to change the credible interval width from the default 95% to a custom level. ```r library(CausalImpact) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) pre.period <- c(1, 70) post.period <- c(71, 100) # Run analysis with 90% credible intervals impact <- CausalImpact(data, pre.period, post.period, alpha = 0.1) # The alpha value is stored in the model print(impact$model$alpha) # [1] 0.1 # Summary will show 90% CI instead of 95% CI summary(impact) ``` -------------------------------- ### Visualize CausalImpact Results Source: https://context7.com/google/causalimpact/llms.txt Generate multi-panel plots for observed data, counterfactual predictions, and causal effects. The plot function returns a ggplot2 object, allowing for further customization. ```r library(CausalImpact) library(ggplot2) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) impact <- CausalImpact(data, c(1, 70), c(71, 100)) # Create default 3-panel plot plot(impact) # Panel 1 (original): Shows observed data (solid) vs counterfactual prediction (dashed) # Panel 2 (pointwise): Shows point-by-point causal effect # Panel 3 (cumulative): Shows cumulative causal effect over time # Select specific panels plot(impact, "original") # Only counterfactual comparison plot(impact, "pointwise") # Only pointwise effects plot(impact, "cumulative") # Only cumulative effects plot(impact, c("original", "pointwise")) # Two panels # Customize the plot (returns ggplot2 object) impact.plot <- plot(impact) + theme_bw(base_size = 20) + labs(title = "Causal Impact of Marketing Campaign") print(impact.plot) # Add custom y-axis label impact.plot <- plot(impact) + ylab("Daily Sales ($)") print(impact.plot) # Access the underlying series data for custom plotting series.data <- as.data.frame(impact$series) head(series.data) ``` -------------------------------- ### Access Time Series Results Source: https://context7.com/google/causalimpact/llms.txt Extract detailed time series data including response, predictions, and effects with credible intervals. Data is returned as a zoo object. ```r library(CausalImpact) library(zoo) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) impact <- CausalImpact(data, c(1, 70), c(71, 100)) # The series field contains all time series data as a zoo object series <- impact$series # Available columns: print(names(series)) # [1] "response" "cum.response" "point.pred" # [4] "point.pred.lower" "point.pred.upper" "cum.pred" # [7] "cum.pred.lower" "cum.pred.upper" "point.effect" # [10] "point.effect.lower" "point.effect.upper" "cum.effect" # [13] "cum.effect.lower" "cum.effect.upper" # Extract specific columns observed <- series$response predicted <- series$point.pred effect <- series$point.effect cumulative_effect <- series$cum.effect # Get post-period effects only post.start <- 71 post.end <- 100 post.effects <- window(series, start = post.start, end = post.end) # Convert to data frame for further analysis df <- as.data.frame(series) df$time <- index(series) # Calculate average effect in post-period mean(series$point.effect[post.start:post.end], na.rm = TRUE) ``` -------------------------------- ### Perform Causal Impact Analysis with Numeric Time Series Source: https://context7.com/google/causalimpact/llms.txt Use this function to perform causal impact analysis on numeric time series data. Ensure your data is in a matrix format with the response variable in the first column and covariates in subsequent columns. Define pre- and post-intervention periods using numeric indices. ```r install.packages("CausalImpact") library(CausalImpact) # Create example data with a response variable (y) and covariate (x1) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 # Add intervention effect of 10 units # Combine into data matrix (response in first column, covariates in subsequent columns) data <- cbind(y, x1) # Define pre-intervention and post-intervention periods pre.period <- c(1, 70) post.period <- c(71, 100) # Run the causal impact analysis impact <- CausalImpact(data, pre.period, post.period) # Access results print(names(impact)) # [1] "series" "summary" "report" "model" # View the time series with predictions head(impact$series) # Returns zoo object with: response, cum.response, point.pred, point.pred.lower, # point.pred.upper, cum.pred, cum.pred.lower, cum.pred.upper, point.effect, # point.effect.lower, point.effect.upper, cum.effect, cum.effect.lower, cum.effect.upper ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.