Package {eventsurvey}


Title: Causal Inference for Events During Surveys
Version: 0.4.2
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.
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
Depends: R (≥ 4.1.0)
Imports: ggplot2, ggthemes
Suggests: dplyr, knitr, pkgdown, rmarkdown, testthat (≥ 3.0.0)
Config/testthat/edition: 3
Config/Needs/website: dplyr, pkgdown, knitr, rmarkdown, ggplot2, ggthemes
VignetteBuilder: knitr
URL: https://yhoriuchi.github.io/eventsurvey/, https://github.com/yhoriuchi/eventsurvey
BugReports: https://github.com/yhoriuchi/eventsurvey/issues
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-11-12 15:54:50 UTC; yh25m
Author: Yusaku Horiuchi ORCID iD [aut, cre], Guoer Liu ORCID iD [aut], Jieun Oh ORCID iD [aut], Yuki Shiraito ORCID iD [aut]
Maintainer: Yusaku Horiuchi <yusaku.horiuchi@gmail.com>
Repository: CRAN
Date/Publication: 2026-12-04 17:40:16 UTC

eventsurvey: Causal Inference for Events During Surveys

Description

The package provides a guided workflow for estimating period-specific and window-average effects when an event occurs during survey fieldwork. The core method forecasts the no-event outcome path from pre-event observations and uses rolling placebo forecasts to assess extrapolation error. The estimator uses a local linear time model, optionally with additive baseline covariates for respondent-level data, and honest bounded-misspecification-error inference.

Author(s)

Maintainer: Yusaku Horiuchi yusaku.horiuchi@gmail.com (ORCID)

Authors:

See Also

Useful links:


Estimate effects of an event during survey fieldwork

Description

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.

Usage

eventsurvey(
  formula,
  data,
  event_time = 0,
  window = 6L,
  event_day = c("exclude", "include"),
  report_event_day = TRUE,
  alpha = 0.05,
  schedule = c("observed", "consecutive")
)

Arguments

formula

A two-sided formula outcome ~ time or outcome ~ time + covariate1 + covariate2, using distinct, untransformed column names. The outcome is numeric and the first right-hand term is time.

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 0, which is appropriate when time is coded relative to the event. Supply the event date or period explicitly when using an absolute time scale.

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 ("exclude", the default) or included in the forecast horizon ("include"). Exclusion is the safer default because exposure is often ambiguous for respondents interviewed during the event period.

report_event_day

If FALSE, an included event period remains in the window-average estimate but is omitted from the printed day-specific results and plots. This argument applies only when event_day = "include".

alpha

Significance level for confidence intervals.

schedule

How rolling fitting and forecasting windows are formed. The default, "observed", forms fitting and forecasting windows from ordered periods containing responses and supports sparse survey schedules. "consecutive" requires every period on the time scale to be represented. In either mode, models use the actual time values rather than compressing gaps.

Details

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.

Value

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.

See Also

vignette("automatic-diagnostics", package = "eventsurvey") for examples of every automatic check and guidance on Review statuses.

Examples

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)
adjusted

Create a complete event-survey report

Description

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.

Usage

eventsurvey_report(
  x,
  file = NULL,
  open = interactive(),
  overwrite = FALSE,
  title = "Event Survey Report"
)

Arguments

x

An object of class eventsurvey, or a non-empty list of such objects. Names identify analyses in a multi-analysis report; missing names are replaced with "Analysis 1", "Analysis 2", and so on.

file

Optional output path. When NULL, the report is written to a temporary file. A .html extension is added when none is supplied.

open

Whether to open the completed report automatically. The default, interactive(), evaluates to TRUE when the function is called from an interactive session such as the RStudio console, and normally evaluates to FALSE in Rscript, tests, continuous integration, and other batch runs. The HTML file is created either way.

overwrite

Whether an existing output file may be replaced.

title

Report title. Defaults to "Event Survey Report".

Value

Invisibly, the normalized path to the generated HTML report.

Examples

if (requireNamespace("rmarkdown", quietly = TRUE) &&
  rmarkdown::pandoc_available()) {
  report_file <- eventsurvey(y ~ day, sample_data) |>
    eventsurvey_report(open = FALSE)
}

Estimate event effects from period-level summaries

Description

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.

Usage

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")
)

Arguments

formula

A two-sided formula of the form period_mean ~ time, using two untransformed column names.

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 n.

variance

The unquoted name of the column containing the within-period sample variance of the outcome. Defaults to a column named variance. It may be NA when n is one; the pooled within-period variance is then used for uncertainty calculations.

event_time

The event period, in the same scale and class as the time variable. Defaults to 0, which is appropriate when time is coded relative to the event. Supply the event date or period explicitly when using an absolute time scale.

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 ("exclude", the default) or included in the forecast horizon ("include"). Exclusion is the safer default because exposure is often ambiguous for respondents interviewed during the event period.

report_event_day

If FALSE, an included event period remains in the window-average estimate but is omitted from the printed day-specific results and plots. This argument applies only when event_day = "include".

alpha

Significance level for confidence intervals.

schedule

How rolling fitting and forecasting windows are formed. The default, "observed", forms fitting and forecasting windows from ordered periods containing responses and supports sparse survey schedules. "consecutive" requires every period on the time scale to be represented. In either mode, models use the actual time values rather than compressing gaps.

Value

An object of class eventsurvey; see eventsurvey().

See Also

vignette("summary-data", package = "eventsurvey") for a complete period-level workflow and an equivalence demonstration.

Examples

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)
}

Extract the window-average event effect and confidence interval

Description

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.

Usage

## S3 method for class 'eventsurvey'
coef(object, ...)

## S3 method for class 'eventsurvey'
confint(
  object,
  parm,
  level = 1 - object$settings$alpha,
  type = c("honest", "conventional"),
  ...
)

Arguments

object

An object returned by eventsurvey() or eventsurvey_summary().

...

Unused.

parm

The coefficient to select. It may be omitted or set to "window_average_effect".

level

Confidence level. By default this is the level used to fit object. Stored intervals cannot be returned at a different level; refit the model with another alpha to change it.

type

Which interval to return: the default honest interval or the conventional interval.

Value

coef() returns a named numeric vector. confint() returns a one-row matrix with lower and upper confidence limits.

Examples

fit <- eventsurvey(y ~ day, sample_data)
coef(fit)
confint(fit)
confint(fit, type = "conventional")

Plot an event-during-survey analysis

Description

Plot an event-during-survey analysis

Usage

## S3 method for class 'eventsurvey'
plot(
  x,
  type = c("counterfactual", "effects", "diagnostics", "coverage", "daily", "counts"),
  inner_level = NULL,
  ...
)

Arguments

x

An eventsurvey object.

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 0.90 when the fitted object contains 95% intervals. The outer interval uses the confidence level supplied when fitting the object.

...

Unused.

Value

A ggplot2 object.


Print an event-during-survey analysis

Description

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.

Usage

## S3 method for class 'eventsurvey'
print(x, ...)

Arguments

x

An object returned by eventsurvey() or eventsurvey_summary().

...

Unused.

Value

Invisibly, x.

See Also

summary.eventsurvey() for detailed numerical output, plot.eventsurvey() for figures, and eventsurvey_report() for a self-contained HTML report.

Examples

fit <- eventsurvey(y ~ day, sample_data)
print(fit)

Published application data at the period level

Description

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.

Usage

published_examples

Format

A data frame with 274 rows and 8 variables:

study

Published study.

outcome

Outcome summarized.

event_date

Date of the event.

date

Interview date.

day

Calendar day relative to the event.

n

Number of non-missing responses.

mean

Daily sample mean.

variance

Daily sample variance; NA when n = 1.

Details

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.

Source

Epifanio, Giani, and Ivandic replication materials: doi:10.7910/DVN/AUHSMD.

References

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

Examples

if (requireNamespace("dplyr", quietly = TRUE)) {
  data(published_examples)
  published_examples |>
    dplyr::filter(grepl("privacy", outcome), dplyr::between(day, -5, 4))
}

Simulated respondent-level survey data

Description

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.

Usage

sample_data

Format

A data frame with 1,496 rows and 2 variables:

day

Interview day relative to the event. Negative values are pre-event, 0 is the event day, and positive values are post-event.

y

Integer-coded five-category survey response from 1 (lowest) to 5 (highest).

Details

Each row represents one respondent. The event occurs at day = 0.

Source

Generated from simulate_eventsurvey(seed = 10) and coded using fixed latent-response thresholds at 45, 48, 51, and 54.

Examples

fit <- eventsurvey(y ~ day, sample_data)
fit

Simulate an event-during-survey dataset

Description

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.

Usage

simulate_eventsurvey(seed = 2026L, pre = 30L, post = 8L, respondents = 40L)

Arguments

seed

Random-number seed.

pre

Number of pre-event periods.

post

Number of event/post-event periods.

respondents

Approximate respondents per period.

Value

A data frame with day, y, counterfactual, and effect.

Examples

if (requireNamespace("dplyr", quietly = TRUE)) {
  dat <- simulate_eventsurvey()
  dat |>
    dplyr::group_by(day) |>
    dplyr::summarise(mean = mean(y), .groups = "drop")
}

Summarize an event-during-survey analysis

Description

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.

Usage

## S3 method for class 'eventsurvey'
summary(object, ...)

Arguments

object

An object returned by eventsurvey() or eventsurvey_summary().

...

Unused.

Value

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.

See Also

print.eventsurvey() for a compact console overview, plot.eventsurvey() for figures, and eventsurvey_report() for a self-contained HTML report.

Examples

fit <- eventsurvey(y ~ day, sample_data)
summary(fit)