| Title: | Causal Inference for Events During Surveys |
|---|---|
| Description: | Provides tools for estimating causal effects when an event occurs while a survey is in the field. The workflow models the unobserved no-event outcome path, evaluates short-horizon forecasts with rolling pre-event exercises, and reports inference that accounts for sampling uncertainty and bounded forecast misspecification. |
| Authors: | Yusaku Horiuchi [aut, cre] (ORCID: <https://orcid.org/0000-0003-0295-4089>), Guoer Liu [aut] (ORCID: <https://orcid.org/0000-0002-7309-9801>), Jieun Oh [aut] (ORCID: <https://orcid.org/0000-0003-2810-0145>), Yuki Shiraito [aut] (ORCID: <https://orcid.org/0000-0003-0264-1138>) |
| Maintainer: | Yusaku Horiuchi <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.2 |
| Built: | 2026-12-04 20:05:22 UTC |
| Source: | https://github.com/cran/eventsurvey |
eventsurvey() extrapolates the pre-event outcome trend into a short
post-event window. It uses rolling pre-event forecasts to bound possible
misspecification and constructs an honest confidence interval using the
union–intersection method.
eventsurvey( formula, data, event_time = 0, window = 6L, event_day = c("exclude", "include"), report_event_day = TRUE, alpha = 0.05, schedule = c("observed", "consecutive") )eventsurvey( formula, data, event_time = 0, window = 6L, event_day = c("exclude", "include"), report_event_day = TRUE, alpha = 0.05, schedule = c("observed", "consecutive") )
formula |
A two-sided formula |
data |
A data frame or tibble with one row per respondent. |
event_time |
The event period, in the same scale and class as the time
variable. Defaults to |
window |
Integer length of both the final pre-event fitting window and the post-event forecast horizon. Must be at least 2. |
event_day |
Whether the event period is excluded so forecasting begins
one period later ( |
report_event_day |
If |
alpha |
Significance level for confidence intervals. |
schedule |
How rolling fitting and forecasting windows are formed. The default,
|
The formula must contain untransformed column names for one numeric outcome
and one time variable, for example support ~ interview_date. Binary
outcomes coded 0/1, ordered responses coded with numeric values such as 1–5,
and continuous outcomes are supported when their period means are
substantively meaningful. Factor and character outcomes must first be
deliberately recoded as numeric. Time may be an integer-like numeric
variable, a Date, or a POSIXt value. Add covariates after time, for example
support ~ interview_date + age + education. Time must be the first term.
Only additive, untransformed columns are supported; interactions and
nonlinear time terms are not supported. Numeric covariates enter linearly;
factors, character columns, and logical columns enter as categorical
indicators (ordered factors are treated as unordered).
With covariates, respondent-level OLS is fitted separately in every rolling and final pre-event window. Predictions are averaged over the covariates of respondents in each forecast period. Use only pre-event characteristics that cannot be affected by the event. The estimand averages the effects for each forecast period's respondent population, weighting periods equally. Adjustment does not automatically identify an effect for a fixed population when survey composition changes.
Covariate-adjusted uncertainty uses stacked respondent influence functions,
centered within periods and corrected by n / (n - 1). This accounts for
estimated covariate means, coefficient uncertainty, and shared observations
across overlapping fits. It conditions on period counts and assumes
independent respondents, allowing heterogeneous variances. Intervals are
asymptotic and additionally require the bounded forecast-misspecification
assumption. Every used period must contain at least two complete responses,
and every fitting window must have full column rank and positive residual
degrees of freedom. Missing outcome, time, or covariates cause complete-case
omission with a warning. Covariates do not guarantee better forecasts or
narrower intervals; inspect rolling errors and choose the specification
without using post-event outcomes.
Both interfaces always use estimand-specific calibration. Each reference
window fits window observed pre-event periods and forecasts at the same
elapsed offsets as the final analysis. All forecast dates must be observed
before the event; no matching windows produces an error.
Estimand-specific calibration uses reference errors at the same elapsed
forecast horizon for each day. Absolute daily population bias must not
exceed the largest absolute matching population reference error.
Sampling uncertainty in reference errors and their covariance with the
daily effect estimate enter each interval. Displayed daily intervals are
pointwise. For the window average, daily effects and daily bias bounds are
averaged with equal weights, after calibration. The average honest interval
averages daily endpoints computed at significance level alpha / window
(Bonferroni), giving conservative joint coverage before aggregation.
The conventional average standard error includes cross-day covariance
induced by the shared pre-event fit. Reference errors are not averaged
across days before calibration.
Every fitted object contains automatic diagnostics. A check receives
"Review" status when calendar periods are missing, any observed period has
fewer than 10 responses, a within-period variance must be pooled, fewer than
five rolling reference windows are available, or an observed-period window
spans more calendar periods than requested. These descriptive flags do not
alter estimates or invalidate an analysis.
An object of class eventsurvey containing the window-average
estimate, honest and conventional intervals, day-specific results,
individual reference forecast errors, rolling-window diagnostics,
automatic checks, daily summaries, and analysis settings.
average_components contains all target days (including an included but
hidden event day), with honest intervals at level 1 - alpha / window
used for the average interval. inference$day_covariance contains the
sampling covariance matrix in target-day order. estimate$n_reference
counts all daily reference contrasts used in aggregation. The days
table includes each day's std_error, elapsed horizon, estimated
bias_bound, and n_reference. Covariate-adjusted fits also contain
reference covariance components in inference, counterfactual_path,
and model_diagnostics. Respondent data are not stored.
vignette("automatic-diagnostics", package = "eventsurvey") for
examples of every automatic check and guidance on Review statuses.
fit <- eventsurvey(y ~ day, sample_data) fit summary(fit) set.seed(42) dat <- sample_data dat$age <- rnorm(nrow(dat), mean = 45, sd = 12) dat$y <- dat$y + 0.2 * (dat$age - 45) adjusted <- eventsurvey(y ~ day + age, dat) adjustedfit <- eventsurvey(y ~ day, sample_data) fit summary(fit) set.seed(42) dat <- sample_data dat$age <- rnorm(nrow(dat), mean = 45, sd = 12) dat$y <- dat$y + 0.2 * (dat$age - 45) adjusted <- eventsurvey(y ~ day + age, dat) adjusted
eventsurvey_report() turns one fitted eventsurvey() or
eventsurvey_summary() object, or a named list of fitted objects, into a
self-contained HTML report. Each analysis retains its own estimates,
diagnostics, settings, and figures.
eventsurvey_report( x, file = NULL, open = interactive(), overwrite = FALSE, title = "Event Survey Report" )eventsurvey_report( x, file = NULL, open = interactive(), overwrite = FALSE, title = "Event Survey Report" )
x |
An object of class |
file |
Optional output path. When |
open |
Whether to open the completed report automatically. The default,
|
overwrite |
Whether an existing output file may be replaced. |
title |
Report title. Defaults to |
Invisibly, the normalized path to the generated HTML report.
if (requireNamespace("rmarkdown", quietly = TRUE) && rmarkdown::pandoc_available()) { report_file <- eventsurvey(y ~ day, sample_data) |> eventsurvey_report(open = FALSE) }if (requireNamespace("rmarkdown", quietly = TRUE) && rmarkdown::pandoc_available()) { report_file <- eventsurvey(y ~ day, sample_data) |> eventsurvey_report(open = FALSE) }
eventsurvey_summary() is the sufficient-statistics counterpart to
eventsurvey(). It is useful when respondent-level observations cannot be
redistributed but each period's count, mean, and sample variance are
available. For a time-only linear model, it produces the same estimates as
the respondent-level function.
Covariate adjustment is available only in eventsurvey(): period counts,
outcome means, and outcome variances do not contain the respondent-level
covariances needed to fit and quantify uncertainty in an adjusted model.
eventsurvey_summary( formula, data, n = n, variance = variance, event_time = 0, window = 6L, event_day = c("exclude", "include"), report_event_day = TRUE, alpha = 0.05, schedule = c("observed", "consecutive") )eventsurvey_summary( formula, data, n = n, variance = variance, event_time = 0, window = 6L, event_day = c("exclude", "include"), report_event_day = TRUE, alpha = 0.05, schedule = c("observed", "consecutive") )
formula |
A two-sided formula of the form |
data |
A data frame or tibble with one row per observed period. |
n |
The unquoted name of the column containing respondent counts.
Defaults to a column named |
variance |
The unquoted name of the column containing the within-period
sample variance of the outcome. Defaults to a column named |
event_time |
The event period, in the same scale and class as the time
variable. Defaults to |
window |
Integer length of both the final pre-event fitting window and the post-event forecast horizon. Must be at least 2. |
event_day |
Whether the event period is excluded so forecasting begins
one period later ( |
report_event_day |
If |
alpha |
Significance level for confidence intervals. |
schedule |
How rolling fitting and forecasting windows are formed. The default,
|
An object of class eventsurvey; see eventsurvey().
vignette("summary-data", package = "eventsurvey") for a complete
period-level workflow and an equivalence demonstration.
if (requireNamespace("dplyr", quietly = TRUE)) { daily <- sample_data |> dplyr::group_by(day) |> dplyr::summarise( mean = mean(y), n = dplyr::n(), variance = stats::var(y), .groups = "drop" ) fit <- eventsurvey_summary(mean ~ day, daily) }if (requireNamespace("dplyr", quietly = TRUE)) { daily <- sample_data |> dplyr::group_by(day) |> dplyr::summarise( mean = mean(y), n = dplyr::n(), variance = stats::var(y), .groups = "drop" ) fit <- eventsurvey_summary(mean ~ day, daily) }
coef() returns the estimated window-average event effect. confint()
returns its honest confidence interval by default; set
type = "conventional" to deliberately request the interval that accounts
for sampling uncertainty but not the estimated misspecification bound.
## S3 method for class 'eventsurvey' coef(object, ...) ## S3 method for class 'eventsurvey' confint( object, parm, level = 1 - object$settings$alpha, type = c("honest", "conventional"), ... )## S3 method for class 'eventsurvey' coef(object, ...) ## S3 method for class 'eventsurvey' confint( object, parm, level = 1 - object$settings$alpha, type = c("honest", "conventional"), ... )
object |
An object returned by |
... |
Unused. |
parm |
The coefficient to select. It may be omitted or set to
|
level |
Confidence level. By default this is the level used to fit
|
type |
Which interval to return: the default honest interval or the conventional interval. |
coef() returns a named numeric vector. confint() returns a
one-row matrix with lower and upper confidence limits.
fit <- eventsurvey(y ~ day, sample_data) coef(fit) confint(fit) confint(fit, type = "conventional")fit <- eventsurvey(y ~ day, sample_data) coef(fit) confint(fit) confint(fit, type = "conventional")
Plot an event-during-survey analysis
## S3 method for class 'eventsurvey' plot( x, type = c("counterfactual", "effects", "diagnostics", "coverage", "daily", "counts"), inner_level = NULL, ... )## S3 method for class 'eventsurvey' plot( x, type = c("counterfactual", "effects", "diagnostics", "coverage", "daily", "counts"), inner_level = NULL, ... )
x |
An |
type |
Plot type: the observed and extrapolated outcome path, period-specific effects, rolling reference errors, combined outcome and response coverage, all period means, or respondent counts by period. In the combined coverage plot, gray bars are scaled relative to the largest period sample and placed in a strip below the observed outcome series. A blue dashed vertical line marks event period 0 in every time-axis plot. |
inner_level |
Optional inner confidence level for an effects plot, such
as |
... |
Unused. |
A ggplot2 object.
Displays a compact console overview containing the formula, window and schedule settings, average effect, honest confidence interval, and number of automatic diagnostic checks requiring review.
## S3 method for class 'eventsurvey' print(x, ...)## S3 method for class 'eventsurvey' print(x, ...)
x |
An object returned by |
... |
Unused. |
Invisibly, x.
summary.eventsurvey() for detailed numerical output,
plot.eventsurvey() for figures, and eventsurvey_report() for a
self-contained HTML report.
fit <- eventsurvey(y ~ day, sample_data) print(fit)fit <- eventsurvey(y ~ day, sample_data) print(fit)
Period-level sufficient statistics used to reproduce the eventsurvey
reanalysis of Epifanio, Giani, and Ivandic (2023). These are derived
summaries, not the original respondent-level replication file. Each row
contains a date's respondent count, outcome mean, and within-date sample
variance.
published_examplespublished_examples
A data frame with 274 rows and 8 variables:
Published study.
Outcome summarized.
Date of the event.
Interview date.
Calendar day relative to the event.
Number of non-missing responses.
Daily sample mean.
Daily sample variance; NA when n = 1.
The Bateson–Weintraub application uses AmericasBarometer data that the package cannot redistribute. Its article instead provides a local data- preparation recipe for authorized users. See the package articles for source links, access conditions, outcome coding, and the distinction between the original studies and these reanalyses.
Epifanio, Giani, and Ivandic replication materials: doi:10.7910/DVN/AUHSMD.
Bateson, Regina, and Michael Weintraub. 2022. "The 2016 Election and America's Standing Abroad: Quasi-experimental Evidence of a Trump Effect." Journal of Politics 84(4): 2300–2304. doi:10.1086/718209
Epifanio, Mariaelisa, Marco Giani, and Ria Ivandic. 2023. "Wait and See? Public Opinion Dynamics after Terrorist Attacks." Journal of Politics 85(3): 843–859. doi:10.1086/723020
if (requireNamespace("dplyr", quietly = TRUE)) { data(published_examples) published_examples |> dplyr::filter(grepl("privacy", outcome), dplyr::between(day, -5, 4)) }if (requireNamespace("dplyr", quietly = TRUE)) { data(published_examples) published_examples |> dplyr::filter(grepl("privacy", outcome), dplyr::between(day, -5, 4)) }
A ready-to-use event-during-survey dataset generated from
simulate_eventsurvey() with seed = 10. Its latent continuous outcome is
coded into a five-category survey response. It provides a simple first
example for eventsurvey() without requiring users to prepare or simulate
data before fitting a model. It contains only variables that would be
observed in an actual survey; the true simulated counterfactual and effect
are intentionally omitted.
sample_datasample_data
A data frame with 1,496 rows and 2 variables:
Interview day relative to the event. Negative values are pre-event, 0 is the event day, and positive values are post-event.
Integer-coded five-category survey response from 1 (lowest) to 5 (highest).
Each row represents one respondent. The event occurs at day = 0.
Generated from simulate_eventsurvey(seed = 10) and coded using
fixed latent-response thresholds at 45, 48, 51, and 54.
fit <- eventsurvey(y ~ day, sample_data) fitfit <- eventsurvey(y ~ day, sample_data) fit
Creates a reproducible respondent-level dataset with a linear no-event trend and heterogeneous post-event effects. It is intended for examples, teaching, and smoke tests rather than power analysis.
simulate_eventsurvey(seed = 2026L, pre = 30L, post = 8L, respondents = 40L)simulate_eventsurvey(seed = 2026L, pre = 30L, post = 8L, respondents = 40L)
seed |
Random-number seed. |
pre |
Number of pre-event periods. |
post |
Number of event/post-event periods. |
respondents |
Approximate respondents per period. |
A data frame with day, y, counterfactual, and effect.
if (requireNamespace("dplyr", quietly = TRUE)) { dat <- simulate_eventsurvey() dat |> dplyr::group_by(day) |> dplyr::summarise(mean = mean(y), .groups = "drop") }if (requireNamespace("dplyr", quietly = TRUE)) { dat <- simulate_eventsurvey() dat |> dplyr::group_by(day) |> dplyr::summarise(mean = mean(y), .groups = "drop") }
Collects and displays the fitted call, analysis settings, automatic diagnostics, window-average estimate, period-specific estimates, and the range and largest absolute value of the rolling reference forecast errors.
## S3 method for class 'eventsurvey' summary(object, ...)## S3 method for class 'eventsurvey' summary(object, ...)
object |
An object returned by |
... |
Unused. |
An object of class summary.eventsurvey containing the fitted call,
settings, estimates, diagnostics, and reference-error summaries. Printing
the returned object displays the complete numerical summary.
print.eventsurvey() for a compact console overview,
plot.eventsurvey() for figures, and eventsurvey_report() for a
self-contained HTML report.
fit <- eventsurvey(y ~ day, sample_data) summary(fit)fit <- eventsurvey(y ~ day, sample_data) summary(fit)