| Title: | Stan-based Poll of Polls Models |
|---|---|
| Description: | Stan Models and code to run Bayesian poll of polls models. |
| Authors: | Mans Magnusson [aut, cre] |
| Maintainer: | Mans Magnusson <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.1 |
| Built: | 2026-09-22 15:14:45 UTC |
| Source: | https://github.com/MansMeg/stanpop |
Assert that the dates are available within the time_line
assert_dates_in_time_line(dates, tl)assert_dates_in_time_line(dates, tl)
dates |
Dates to check |
tl |
A [time_line] object to check against |
Assert that the poll_data object dates are available within the time_line
assert_poll_data_in_time_line(pd, tl)assert_poll_data_in_time_line(pd, tl)
pd |
[polls_data] to check if part of [time_line] |
tl |
[time_line] to check against |
The assertion creates a [time_line] using the [time_scale]
assert_poll_data_in_time_line_using_time_scale(pd, ts) assert_poll_data_in_time_line_using_time_range(pd, ts, tr)assert_poll_data_in_time_line_using_time_scale(pd, ts) assert_poll_data_in_time_line_using_time_range(pd, ts, tr)
pd |
[polls_data] to check if part of [time_line] |
ts |
a time_scale to use |
tr |
a [time_range] |
[time_range()]
Check Stan Data for specific model
assert_stan_data_model(x) ## S3 method for class 'model2' assert_stan_data_model(x) ## S3 method for class 'model3' assert_stan_data_model(x) ## S3 method for class 'model5' assert_stan_data_model(x) ## S3 method for class 'model6' assert_stan_data_model(x) ## S3 method for class 'model6b' assert_stan_data_model(x) ## S3 method for class 'model8a' assert_stan_data_model(x) ## S3 method for class 'model8a1' assert_stan_data_model(x) ## S3 method for class 'model8a3' assert_stan_data_model(x) ## S3 method for class 'model8c' assert_stan_data_model(x) ## S3 method for class 'model8b' assert_stan_data_model(x) ## S3 method for class 'model8d' assert_stan_data_model(x) ## S3 method for class 'model8e' assert_stan_data_model(x) ## S3 method for class 'model8f' assert_stan_data_model(x) ## S3 method for class 'model8g' assert_stan_data_model(x) ## S3 method for class 'model8i' assert_stan_data_model(x) ## S3 method for class 'model8k' assert_stan_data_model(x) ## S3 method for class 'model8l' assert_stan_data_model(x) ## S3 method for class 'model8m' assert_stan_data_model(x) ## S3 method for class 'model2' assert_stan_data_model(x) ## S3 method for class 'model5' assert_stan_data_model(x) ## S3 method for class 'model3' assert_stan_data_model(x) ## S3 method for class 'model4' assert_stan_data_model(x) ## S3 method for class 'model9' assert_stan_data_model(x)assert_stan_data_model(x) ## S3 method for class 'model2' assert_stan_data_model(x) ## S3 method for class 'model3' assert_stan_data_model(x) ## S3 method for class 'model5' assert_stan_data_model(x) ## S3 method for class 'model6' assert_stan_data_model(x) ## S3 method for class 'model6b' assert_stan_data_model(x) ## S3 method for class 'model8a' assert_stan_data_model(x) ## S3 method for class 'model8a1' assert_stan_data_model(x) ## S3 method for class 'model8a3' assert_stan_data_model(x) ## S3 method for class 'model8c' assert_stan_data_model(x) ## S3 method for class 'model8b' assert_stan_data_model(x) ## S3 method for class 'model8d' assert_stan_data_model(x) ## S3 method for class 'model8e' assert_stan_data_model(x) ## S3 method for class 'model8f' assert_stan_data_model(x) ## S3 method for class 'model8g' assert_stan_data_model(x) ## S3 method for class 'model8i' assert_stan_data_model(x) ## S3 method for class 'model8k' assert_stan_data_model(x) ## S3 method for class 'model8l' assert_stan_data_model(x) ## S3 method for class 'model8m' assert_stan_data_model(x) ## S3 method for class 'model2' assert_stan_data_model(x) ## S3 method for class 'model5' assert_stan_data_model(x) ## S3 method for class 'model3' assert_stan_data_model(x) ## S3 method for class 'model4' assert_stan_data_model(x) ## S3 method for class 'model9' assert_stan_data_model(x)
x |
a [poll_of_polls] object |
Return indicator on polls without missing values
complete_poll_info(x) complete_poll_data(x) complete_poll_y(x) complete_polls(x)complete_poll_info(x) complete_poll_data(x) complete_poll_y(x) complete_polls(x)
x |
a [polls_data] object. |
[complete_poll_info()] indicate polls with complete poll_info.
[complete_poll_data()] and [complete_poll_y()] indicate polls with complete poll data (or y)
[complete_polls()] indicate polls with complete poll data and info
a boolean vector
Compute the default value of g_scale
compute_g_scale_default(x)compute_g_scale_default(x)
x |
a list with g and next_known_state_index |
Compute gamma parameters with same expectation and variances as a half-normal with parameter sigma
compute_gamma_parameters(sigma, n = 1e+06)compute_gamma_parameters(sigma, n = 1e+06)
sigma |
the sigma parameter in a half-formal |
n |
how many samples to approximate the half-normal |
a list with parameters a and b
Compute prediction error for a poll_of_polls model
compute_prediction_error(x, predict_state, type = "elpd")compute_prediction_error(x, predict_state, type = "elpd")
x |
a [poll_of_polls] model |
predict_state |
the true value to predict |
type |
error measurement to compute |
Go through all unconstrained indecies and return all parameters that changes due to the constrained parameter.
Note that in a state space model a unconstrated parameter can change a whole series due to the model formulation.
create_constrained_names_to_unconstrained_idx_map(x, return_first = FALSE)create_constrained_names_to_unconstrained_idx_map(x, return_first = FALSE)
x |
a poll of polls object |
return_first |
return the first character element (the unconstrained, non-transformed parameter) |
Semi-automatic construction of parameters for specific models
create_unpar_one_to_one_map(x)create_unpar_one_to_one_map(x)
x |
a poll of polls object |
Create the names of the unconstrained parameters from specific models
Curate the Swedish polls dataset
curate_swedish_polls( x, parties = c("M", "L", "C", "KD", "S", "V", "MP", "SD", "FI") )curate_swedish_polls( x, parties = c("M", "L", "C", "KD", "S", "V", "MP", "SD", "FI") )
x |
a SwedishPolls data.frame |
parties |
parties to curate |
What dates are available within the time_line
dates_in_time_line(dates, tl)dates_in_time_line(dates, tl)
dates |
Dates to check |
tl |
A [time_line] object to check against |
Extract minimal eigen value per iteration
diagnose_extract_min_eigen_value_Omega(x)diagnose_extract_min_eigen_value_Omega(x)
x |
a [poll_of_polls] object |
Extract the percentiles of the divergent transistions
divergent_transitions_percentiles(x)divergent_transitions_percentiles(x)
x |
a [poll_of_polls] object |
a matrix of the percentiles of the divergent transitions
Compute the elpd, percentiles and rmse for a true [known_state]
elpd_known_state(x, known_state) ## S3 method for class 'pop_model8f1' elpd_known_state(x, known_state) ## S3 method for class 'pop_model8f2' elpd_known_state(x, known_state) rmse_known_state(x, known_state) percentile_known_state(x, known_state)elpd_known_state(x, known_state) ## S3 method for class 'pop_model8f1' elpd_known_state(x, known_state) ## S3 method for class 'pop_model8f2' elpd_known_state(x, known_state) rmse_known_state(x, known_state) percentile_known_state(x, known_state)
x |
a [poll_of_polls] object |
known_state |
a [known_state] object |
Incorrect draws has been removed
Return parties existing in a given model range
existing_parties(y, ltr, mtr)existing_parties(y, ltr, mtr)
y |
a character vector of party names |
ltr |
the [time_range] of the latent series |
mtr |
the [time_range] of the model |
Extract parameters from the stan object
extract(object, ...) ## S3 method for class 'poll_of_polls' extract(object, ...)extract(object, ...) ## S3 method for class 'poll_of_polls' extract(object, ...)
object |
an object to extract parameter draws from |
... |
arguments supplied to rstan::extract. |
'extract_poll_of_polls_refit_arguments()' returns the named constructor arguments for [poll_of_polls()] that are stored in a [poll_of_polls] object. Unlike 'x$input_args', the returned list excludes backend sampler arguments from '...', which are returned separately by [extract_poll_of_polls_sample_arguments()].
'extract_poll_of_polls_input_arguments()' is retained as a backward-compatible alias and returns the same refit-ready constructor arguments.
extract_poll_of_polls_refit_arguments(x) extract_poll_of_polls_input_arguments(x) extract_poll_of_polls_sample_arguments(x)extract_poll_of_polls_refit_arguments(x) extract_poll_of_polls_input_arguments(x) extract_poll_of_polls_sample_arguments(x)
x |
A pop object. |
'extract_poll_of_polls_refit_arguments()' and 'extract_poll_of_polls_input_arguments()' return a list with the named [poll_of_polls()] constructor arguments, excluding sampler arguments from '...'.
'extract_poll_of_polls_sample_arguments()' returns the sampler arguments that were supplied through '...' when the model was fit.
Deprecated. This helper encodes an older fixed-length election-period marker. New code should instead use [get_known_state_periods()] or [get_known_state_lookback_windows()] and apply any report-specific window naming or presentation downstream.
extract_pop_election_period(pop, election_period_length = 6)extract_pop_election_period(pop, election_period_length = 6)
pop |
a poll of polls object |
election_period_length |
the number of time points that make up the lection period |
Kept for backward compatibility. It still returns a tibble with the election period as a boolean per time point.
[get_known_state_periods()], [get_known_state_lookback_windows()]
Extract mean x change from a poll_of_polls object
extract_pop_empirical_posterior_mean_x_change(pop, type)extract_pop_empirical_posterior_mean_x_change(pop, type)
pop |
a poll of polls object |
type |
type of |
Extracts the difference in the latent state between time points, either as the [diff]erence x[t]-x[t-1] or the [ratio] x[t]/x[t-1]. Here t=1 is set to NA.
Format election period lists to string for printout
format_election_period_to_string(x, period_marker = "--", collapse = NULL)format_election_period_to_string(x, period_marker = "--", collapse = NULL)
x |
a poll of polls object |
period_marker |
character used to combine election period dates to an election period |
collapse |
should the election periods be collapsed to a character of length one (NULL if not), then the string used to collapse the character vector elements. |
Format obs_x lists to string for printout
format_obs_x_to_string(x, collapse = NULL)format_obs_x_to_string(x, collapse = NULL)
x |
a poll of polls object |
collapse |
should the obs_x characters be collapsed to a character of length one (NULL if not), then the string used to collapse the character vector elements. |
Visualize a known state in a poll_of_polls ggplot
geom_known_state(x, y, ...)geom_known_state(x, y, ...)
x |
a known_states data.frame |
y |
the specific variable to visualize |
... |
further arguments to geom_line and geom_point |
Add a [latent_state] geom to a ggplot
geom_latent_state( x, median = TRUE, intervals = c(0.9, 0.75, 0.5), latent_state_colour = "darkgrey", ... )geom_latent_state( x, median = TRUE, intervals = c(0.9, 0.75, 0.5), latent_state_colour = "darkgrey", ... )
x |
a [latent_state] object |
median |
should the median be plotted? |
intervals |
what intervals should be visualized |
latent_state_colour |
the color of the latent state |
... |
further arguments to [geom_ribbon] and [geom_line]. |
Constructs a tibble with the weight of each day of a poll. The tibble can then be aggregated to the right level time scale. The first day of each year, month and week is used to set a date for each time point.
geom_polls_time_weights(x, y, ...) polls_time_weights(x, ...) ## S3 method for class 'polls_data' polls_time_weights(x, week_start = 1, ...) ## S3 method for class 'stan_polls_data' polls_time_weights(x, ...) polls_time_weights(x) <- value ## S3 replacement method for class 'polls_data' polls_time_weights(x) <- valuegeom_polls_time_weights(x, y, ...) polls_time_weights(x, ...) ## S3 method for class 'polls_data' polls_time_weights(x, week_start = 1, ...) ## S3 method for class 'stan_polls_data' polls_time_weights(x, ...) polls_time_weights(x) <- value ## S3 replacement method for class 'polls_data' polls_time_weights(x) <- value
x |
a [polls_data] object. |
y |
a vector to plot for the [polls_time_weights] object. |
... |
further arguments to [geom_point] |
week_start |
day on which week starts following ISO conventions - 1 means Monday, 7 means Sunday (default). |
value |
a [polls_time_weights] object. |
a [polls_time_weights] object (tibble)
Visualize a stan_data object
geom_stan_polls_data(x, ...)geom_stan_polls_data(x, ...)
x |
a [stan_polls_data] object |
... |
further arguments supplied to [geom_polls_time_weights()]. |
stan_polls_data
German election data
german_electionsgerman_elections
A data frame with 4 elections, 2005-2017
German polls data
german_polls german_polls_curatedgerman_polls german_polls_curated
A data frame with 4609 polls and 6 parties:
An object of class data.frame with 4606 rows and 15 columns.
http://www.wahlrecht.de/umfragen/
Extract the adaptation info (step size and diagonal invers mass matrix) from a [poll_of_polls] object
get_adaptation_info(x, as.list = FALSE, ...)get_adaptation_info(x, as.list = FALSE, ...)
x |
a [poll_of_polls] |
as.list |
return an R list. Defaults to [FALSE]. |
... |
further arguemt past to [rstan::get_adaptation_info] |
The first poll is the poll with the earliest starting date
get_first_poll_as_simplex(x)get_first_poll_as_simplex(x)
x |
a stan_data object |
Return one lookback window per usable known-state evaluation date.
get_known_state_lookback_windows(pop, window = lubridate::period(months = 6))get_known_state_lookback_windows(pop, window = lubridate::period(months = 6))
pop |
a [poll_of_polls] object |
window |
a scalar lubridate [Period] defining how far back each lookback window should start. |
This helper builds directly on [get_known_state_periods()] so lookback windows use the same stable set of usable evaluation dates. The 'window' argument must be a scalar lubridate [Period], for example 'lubridate::period(months = 6)' or 'lubridate::days(180)'.
Lookback window semantics are:
1. 'window_to' is the current 'evaluation_date', 2. 'window_from' is 'evaluation_date' shifted backward by 'window', and 3. the returned rows retain the matching period metadata.
Calendar-aware month arithmetic is computed with 'lubridate::%m-%' so month-based lookback windows behave consistently around month ends.
A tibble with one row per usable known-state date and the columns 'window_index', 'evaluation_date', 'window_from', 'window_to', 'period_index', 'previous_evaluation_date', 'period_from', 'period_to', and 'is_last'.
Return one general evaluation period per usable known-state date.
get_known_state_periods(pop)get_known_state_periods(pop)
pop |
a [poll_of_polls] object |
This function extract stable period definition. A usable evaluation date is a non-missing known-state date on or before the model end date. Returned dates are sorted and deduplicated before periods are constructed.
The period semantics are intentionally conservative:
1. 'period_to' is the current 'evaluation_date', 2. 'period_from' is the previous 'evaluation_date', and 3. the first period gets 'NA' for 'previous_evaluation_date' and 'period_from'.
A tibble with one row per usable known-state date and the columns 'period_index', 'evaluation_date', 'previous_evaluation_date', 'period_from', 'period_to', and 'is_last'.
Return the model end date together with the latest known-state date that can be used for evaluation.
get_last_evaluation_info(pop)get_last_evaluation_info(pop)
pop |
a [poll_of_polls] object |
This helper exists to extract definition of the "last evaluation window" instead of recomputing it ad hoc. In practice, reports often need to know:
1. when the fitted latent series ends, 2. what the most recent usable known-state date is, and 3. how many days separate those two dates.
A one-row tibble with 'model_time_to', 'evaluation_date', and 'gap_days'. When there is no known state on or before the model end date, 'evaluation_date' and 'gap_days' are returned as missing values.
Get the latent state for specific dates
get_latent_state_for_dates(x, date)get_latent_state_for_dates(x, date)
x |
a [poll_of_polls] or [latent_state] object |
date |
a [date] vector |
Get the model diagnostics used in a [poll_of_polls] object
get_model_diagnostics(x)get_model_diagnostics(x)
x |
a [poll_of_polls] object |
no_divergent_transitions: The number of draws with divergent transitions no_max_treedepth: The number of draws where the max treedepth was reached no_low_bfmi_chains: The number of chains with low E-BFMI no_Rhat_above_1_1: The number of parameters with an Rhat above 1.1 no_Rhat_is_NA: The number of parameters without an Rhat value mean_no_leapfrog_steps: The mean number of leapfrog steps taken per iteration/draw mean_chain_step_size: The mean stepsize over the chains mean_chain_inv_mass_matrix_min_max: The mean max and min of the invers mass matrix over the chains mean_chain_warmup_time: the mean warmup time in seconds mean_chain_sampling_time: the mean warmup time in seconds
a list with diagnostic values
Get the model arguments used in a [poll_of_polls] object
get_model_model_arguments(x, all = TRUE)get_model_model_arguments(x, all = TRUE)
x |
a [poll_of_polls] object |
all |
Should all model arguments be returned, or just the one that were set? |
a list with model arguments
Get the number of draws/samples in a [poll_of_polls] object
get_ndraws(x) ndraws(x)get_ndraws(x) ndraws(x)
x |
a [poll_of_polls] object |
Get the next known state index
get_polls_next_known_state_index(x, known_state, type = "collection_midpoint") get_time_line_next_known_state_index(time_line, known_state) get_dates_next_known_state_index(dates, known_state)get_polls_next_known_state_index(x, known_state, type = "collection_midpoint") get_time_line_next_known_state_index(time_line, known_state) get_dates_next_known_state_index(dates, known_state)
x |
a [polls_data] object |
known_state |
a [known_state] object |
type |
how is the next state index defined. Default is based on [collection_period] dates. |
time_line |
time line to get next index for |
dates |
Dates to get next index for |
The function returns the index for the next known state. Polls without a next unknown state, gets index [nrow(known_state) + 1].
Get the number of time points between known state
get_polls_time_points_between_known_states( x, known_state, tl, type = "collection_midpoint" ) get_time_line_time_points_between_known_states(tl, known_state) get_dates_time_points_between_known_states(dates, known_state, tl)get_polls_time_points_between_known_states( x, known_state, tl, type = "collection_midpoint" ) get_time_line_time_points_between_known_states(tl, known_state) get_dates_time_points_between_known_states(dates, known_state, tl)
x |
a [polls_data] object |
known_state |
a [known_state] object |
tl |
a [time_line] object to get the number of time points between known state |
type |
how is the next state index defined. Default is based on [collection_period] dates. |
dates |
Dates to get the number of time points between known states |
The function returns the number of time points between the known states.
Get the number of time points since the last known state
get_polls_time_points_since_last_known_state( x, known_state, tl, type = "collection_midpoint" ) get_time_line_time_points_since_last_known_state(tl, known_state) get_dates_time_points_since_last_known_state(dates, known_state, tl)get_polls_time_points_since_last_known_state( x, known_state, tl, type = "collection_midpoint" ) get_time_line_time_points_since_last_known_state(tl, known_state) get_dates_time_points_since_last_known_state(dates, known_state, tl)
x |
a [polls_data] object |
known_state |
a [known_state] object |
tl |
a [time_line] object to get the number of time points since last known state |
type |
how is the next state index defined. Default is based on [collection_period] dates. |
dates |
Dates to get the number of time points since the last known state |
The function returns the number of time points since the last known state.
Get Sampler Diagnostics
get_sampler_params(object, ...) ## S3 method for class 'poll_of_polls' get_sampler_params(object, ...)get_sampler_params(object, ...) ## S3 method for class 'poll_of_polls' get_sampler_params(object, ...)
object |
a [poll_of_polls] object to extract stan samples from |
... |
arguments further supplied to [rstan::get_sampler_params()] |
rstan::get_sampler_params
Extract the date when Stan was run
get_stan_date(object)get_stan_date(object)
object |
a [poll_of_polls] object |
Get Stan Code from a pop object
get_stancode(object, ...) ## S3 method for class 'poll_of_polls' get_stancode(object, ...)get_stancode(object, ...) ## S3 method for class 'poll_of_polls' get_stancode(object, ...)
object |
a [poll_of_polls] object to extract stan code from |
... |
arguments further supplied to [rstan::get_stancode()] |
rstan::get_stancode
Get time line from polls or time range
get_time_line(x, time_range, time_scale)get_time_line(x, time_range, time_scale)
x |
a [polls_data] object |
time_range |
a time range object |
time_scale |
a time_scale |
Get the time points for specific dates
get_time_points(x, dates) ## S3 method for class 'time_line' get_time_points(x, dates) ## S3 method for class 'poll_of_polls' get_time_points(x, dates)get_time_points(x, dates) ## S3 method for class 'time_line' get_time_points(x, dates) ## S3 method for class 'poll_of_polls' get_time_points(x, dates)
x |
a [time_line] or [poll_of_polls] |
dates |
a [date] vector |
Look up one index value from the [daily] table of a [time_line] object for each date in [dates]. This is typically used to convert calendar dates to latent time-point indices such as [time_line_t].
get_time_points_from_time_line(dates, tl, return_variable = "time_line_t") get_total_time_points_from_time_line(tl)get_time_points_from_time_line(dates, tl, return_variable = "time_line_t") get_total_time_points_from_time_line(tl)
dates |
a vector with dates to convert to time points |
tl |
a [time_line] object |
return_variable |
the daily variable (time point type) to return |
The house levels are extracted in the same order as h_i in the stan data object.
house_levels(x) party_levels(x)house_levels(x) party_levels(x)
x |
a [poll_of_polls] object |
Map between houses and house names
house_maphouse_map
A data.frame with house, house name and country.:
What samples are correct?
incorrect_draws(x)incorrect_draws(x)
x |
a [poll_of_polls] object |
Create a latent state object
latent_state(x, time_line = NULL, ...) ## S3 method for class 'poll_of_polls' latent_state(x, time_line = NULL, ...) ## S3 method for class 'stanfit' latent_state(x, time_line, dimnames, ...)latent_state(x, time_line = NULL, ...) ## S3 method for class 'poll_of_polls' latent_state(x, time_line = NULL, ...) ## S3 method for class 'stanfit' latent_state(x, time_line, dimnames, ...)
x |
an object to convert to a [latent_state] |
time_line |
a [time_line] object |
... |
further arguments to methods |
dimnames |
The dimnames attribute for the latent state array |
Bind latent_state objects
latent_state_abind(x, y, along, ...)latent_state_abind(x, y, along, ...)
x |
a [latent_state] object |
y |
a [latent_state] object |
along |
the dimension to bind the latent states. See [abind::abind] for details. |
... |
further arguments to [abind::abind] |
a [latent_state] object
Apply latent_state objects
latent_state_apply(x, MARGIN, FUN, ...)latent_state_apply(x, MARGIN, FUN, ...)
x |
a [latent_state] object to subet |
MARGIN |
margins to apply over |
FUN |
function to apply |
... |
further arguments to base::apply |
a [latent_state] object
Compute an arbitrary function of latent states
latent_state_FUN(x, FUN, var_name) ## S3 method for class 'poll_of_polls' latent_state_FUN(x, FUN, var_name) ## S3 method for class 'latent_state' latent_state_FUN(x, FUN, var_name)latent_state_FUN(x, FUN, var_name) ## S3 method for class 'poll_of_polls' latent_state_FUN(x, FUN, var_name) ## S3 method for class 'latent_state' latent_state_FUN(x, FUN, var_name)
x |
a latent state |
FUN |
an arbitrary function |
var_name |
the variable name to use |
Compute functions of the latent state
latent_state_percentiles(x, percentiles) latent_state_mean(x) latent_state_draw(x, draw_idx) latent_state_sd(x) latent_state_mean_dates(x, dates)latent_state_percentiles(x, percentiles) latent_state_mean(x) latent_state_draw(x, draw_idx) latent_state_sd(x) latent_state_mean_dates(x, dates)
x |
a [latent_state] |
percentiles |
percentiles to compute |
draw_idx |
a draw index from the posterior |
dates |
a vector of date values |
Subset latent_state objects
latent_state_subset(x, iterations = NULL, t = NULL, categories = NULL)latent_state_subset(x, iterations = NULL, t = NULL, categories = NULL)
x |
a [latent_state] object to subet |
iterations |
subset iterations |
t |
subset time points (t) |
categories |
subset categories |
a [latent_state] object
Read a wrapped '.rds' file created by [save_pop()] and return the stored [poll_of_polls] object. Files not created by [save_pop()] are rejected so the loader can rely on the wrapper metadata and avoid silently accepting arbitrary serialized objects.
load_pop(file)load_pop(file)
file |
Path to a file previously created by [save_pop()]. |
A [poll_of_polls] object.
Stan Function for pop objects
log_prob(object, ...) ## S3 method for class 'poll_of_polls' log_prob(object, ...) ## Default S3 method: log_prob(object, ...) get_num_upars(object, ...) ## S3 method for class 'poll_of_polls' get_num_upars(object, ...) ## Default S3 method: get_num_upars(object, ...) get_num_pars(object)log_prob(object, ...) ## S3 method for class 'poll_of_polls' log_prob(object, ...) ## Default S3 method: log_prob(object, ...) get_num_upars(object, ...) ## S3 method for class 'poll_of_polls' get_num_upars(object, ...) ## Default S3 method: get_num_upars(object, ...) get_num_pars(object)
object |
an object |
... |
arguments supplied to the rstan function |
Extract the data when Stan was run
logMeanExp(x)logMeanExp(x)
x |
a numeric vector of loged values |
Set default values and assert arguments for a model configuration
model_config(model, x = NULL, stan_data = NULL) model_arguments(model)model_config(model, x = NULL, stan_data = NULL) model_arguments(model)
model |
the model for which to set the model arguments |
x |
a list with model arguments (the model config) set by the user |
stan_data |
a list with the stan data used for the model |
With model arguments, the arguments that are set by the user for each poll_of_polls stan model. This differs between models. See [model_arguments()] for the model arguments used by each model.
Return a data.frame with dates from a list of pop objects
model_dates_data_frame(x)model_dates_data_frame(x)
x |
a list of pop objects |
Extract the parameter names and parameter counts from a poll_of_polls object
parameter_names(x, rm_idx = FALSE) extract_parameter_names(x, rm_idx = FALSE) parameter_block_names(x) parameters_counts(x) get_parameter_names(x, rm_idx = FALSE)parameter_names(x, rm_idx = FALSE) extract_parameter_names(x, rm_idx = FALSE) parameter_block_names(x) parameters_counts(x) get_parameter_names(x, rm_idx = FALSE)
x |
a [poll_of_polls] object |
rm_idx |
remove parameter indecies (e.g. [1], [1,1], [1,1,1]) from the parameter names. Default is FALSE. |
The function returns the name and indecies of all parameters on the constrained space that are affected by the unconstrained parameter.
parameter_names_from_unconstrained_index(stanfit, up_idx) parameter_block_names_from_unconstrained_index(stanfit, up_idx) parameter_unique_names_from_unconstrained_index(stanfit, up_idx)parameter_names_from_unconstrained_index(stanfit, up_idx) parameter_block_names_from_unconstrained_index(stanfit, up_idx) parameter_unique_names_from_unconstrained_index(stanfit, up_idx)
stanfit |
a [stanfit] object to extract parameter names from |
up_idx |
the index of parameters at the constrained space to extract names for |
a [data.frame] with one row per parameter affected by the unconstrained
Parse a data frame of observed x (t distributed)
parse_obs_x(hyper_parameters, time_line, y_name)parse_obs_x(hyper_parameters, time_line, y_name)
hyper_parameters |
a list that contains the slot obs_x with the dataframe |
time_line |
the time_line to use to parse dates to time points |
y_name |
the different values used to parse obs_x$y to integers |
A subset of swe_polls stored as a [polls_data] object
pd_testpd_test
a [polls_data] object with 1007 polls.
All polls from [swe_polls] without missing data during 2010-01-01 to 2019-12-31. See data-raw folder for exact construction.
Plot posterior distributions of parameters
plot_parameters_areas( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_hex( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_scatter( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_intervals( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) ## S3 method for class 'poll_of_polls' pairs(x, ...) traceplot(x, ...) ## S3 method for class 'poll_of_polls' traceplot(x, pars = NULL, inc_warmup = FALSE, ...)plot_parameters_areas( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_hex( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_scatter( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) plot_parameters_mcmc_intervals( x, params, params_plot_name = NULL, title = "Posterior distributions", ... ) ## S3 method for class 'poll_of_polls' pairs(x, ...) traceplot(x, ...) ## S3 method for class 'poll_of_polls' traceplot(x, pars = NULL, inc_warmup = FALSE, ...)
x |
a [poll_of_polls] object |
params |
parameters to plot (see |
params_plot_name |
names to use for parameters in plot |
title |
The title of the plot. |
... |
further arguments sent to bayesplot::mcmc_areas, bayesplot::mcmc_hex, etc. |
pars |
optional parameter names to include in the traceplot. |
inc_warmup |
should warmup draws be included when constructing the traceplot input? |
Plot posterior distributions of parameters
plot_parameters_bayesplot( x, bayeplot_FUN, params, params_plot_name = NULL, ... )plot_parameters_bayesplot( x, bayeplot_FUN, params, params_plot_name = NULL, ... )
x |
a [poll_of_polls] object |
bayeplot_FUN |
a plotting function from the basyeplot package |
params |
parameters to plot (see |
params_plot_name |
names to use for parameters in plot |
... |
further arguments sent to bayesplot::mcmc_area |
Plot a [poll_of_polls] object
plot_poll_of_polls( x, y = NULL, from = NULL, to = NULL, publish_date = TRUE, collection_period = FALSE, shift_latent_days = 0, house = NULL, include_latent_state = TRUE, latent_date_position = c("period_start", "period_end"), ... ) ## S3 method for class 'poll_of_polls' plot(x, ...) geom_pop_line(x, y, ...)plot_poll_of_polls( x, y = NULL, from = NULL, to = NULL, publish_date = TRUE, collection_period = FALSE, shift_latent_days = 0, house = NULL, include_latent_state = TRUE, latent_date_position = c("period_start", "period_end"), ... ) ## S3 method for class 'poll_of_polls' plot(x, ...) geom_pop_line(x, y, ...)
x |
a [poll_of_polls] object |
y |
column to visualize. |
from |
plot from [date] |
to |
plot to [date] |
publish_date |
visualize publication dates. |
collection_period |
visualize collection period. |
shift_latent_days |
Shift the latent series right, this number of days. |
house |
only plot the following polling houses |
include_latent_state |
include latent state in plot |
latent_date_position |
Where to display latent-state dates. '"period_start"' uses the latent anchor/start dates stored in the timeline. '"period_end"' uses the last daily date mapped to each latent time point, which is aware of mixed time-scale timelines. |
... |
further arguments to [geom_line] |
Plot a [polls_data] object
## S3 method for class 'polls_data' plot(x, y = NULL, publish_date = TRUE, collection_period = TRUE, ...) geom_publish_date(x, y, ...) geom_collection_period(x, y, ...)## S3 method for class 'polls_data' plot(x, y = NULL, publish_date = TRUE, collection_period = TRUE, ...) geom_publish_date(x, y, ...) geom_collection_period(x, y, ...)
x |
a [polls_data] object |
y |
a variable name in the [polls_data] object. |
publish_date |
visualize publication dates. |
collection_period |
visualize collection period. |
... |
further arguments to [geom_collection_period] |
Get and set elements of a [data_polls] object
poll_id(x) poll_ids(x) poll_id(x) <- value poll_ids(x) <- value start_date(x) start_dates(x) start_date(x) <- value start_dates(x) <- value end_date(x) end_dates(x) end_date(x) <- value end_dates(x) <- value publish_date(x) publish_dates(x) publish_date(x) <- value publish_dates(x) <- value n(x) collection_midpoint_dates(x) houses(x) n(x) <- value y(x) y(x) <- valuepoll_id(x) poll_ids(x) poll_id(x) <- value poll_ids(x) <- value start_date(x) start_dates(x) start_date(x) <- value start_dates(x) <- value end_date(x) end_dates(x) end_date(x) <- value end_dates(x) <- value publish_date(x) publish_dates(x) publish_date(x) <- value publish_dates(x) <- value n(x) collection_midpoint_dates(x) houses(x) n(x) <- value y(x) y(x) <- value
x |
a [data_polls] object. |
value |
a value to set. |
Fit a poll of polls object
poll_of_polls( y, model, polls_data, time_scale, time_scale_overrides = NULL, known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL, backend = "rstan", compile_args = NULL, ..., cache_dir = file.path(tempdir(), "pop_cache") )poll_of_polls( y, model, polls_data, time_scale, time_scale_overrides = NULL, known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL, backend = "rstan", compile_args = NULL, ..., cache_dir = file.path(tempdir(), "pop_cache") )
y |
character vector indicating poll variable to use |
model |
poll of polls model to use (or a path to a stan model) |
polls_data |
a [polls_data] object |
time_scale |
the time scale to use, [day], [week], or [month]. |
time_scale_overrides |
a [data.frame] with columns [from], [to], and [time_scale] that override the default [time_scale] for inclusive date ranges in the latent state. The [from] and [to] bounds are inclusive and override ranges must not overlap. |
known_state |
a [data.frame] with variables [date] and [x] indicating the known states for certain dates. |
model_time_range |
a [time_range] object that describe the period used for the latent state. Default is the [time_range] of the [polls_data] object. |
latent_time_ranges |
time ranges of the latent state of individual [y]s |
hyper_parameters |
hyperparameters to supply direct to the model |
slow_scales |
a vector of [Date]s that indicate breaks (right-inclusive) for a slower moving time scale. |
backend |
Stan backend to use. Supported values are [rstan] and [cmdstanr]. |
compile_args |
additional arguments passed to [cmdstanr::cmdstan_model()] when 'backend = "cmdstanr"'. Ignored for 'backend = "rstan"'. |
... |
further arguments passed directly to the backend sampler. These go to [rstan::stan()] when 'backend = "rstan"' and to 'CmdStanModel$sample()' when 'backend = "cmdstanr"'. |
cache_dir |
directory to cache model. Default is cache in tempdir(). [NULL], no cache. Cached objects are stored with [save_pop()] in the same wrapped on-disk format used by the public save/load API. Existing cache files at the same hash are replaced when it reaches the save step. |
The [input_args] slot contain all input arguments except polls data and known state that are stored in the original object instead. The [stan_arguments] slot contains the backend sampling arguments supplied through '...', except for the 'data' argument which is stored in the [stan_data] slot. The [compile_arguments] slot contains the CmdStanR compilation arguments. The [warm_start_state] slot caches the reusable warm-start payload extracted from the fitted Stan object so future refits do not need to recover it from the backend fit after serialization.
For 'model8m10', 'hyper_parameters' can include 'structural_bridge_type', 'structural_bridge_window', 'structural_bridge_x_target_path', 'structural_bridge_alpha_week', 'structural_bridge_sigma_scale', and 'structural_bridge_epsilon'. Type 0 means no bridge, type 1 or '"x_drift"' enables a state-dependent x-scale drift for selected parties, and type 2 or '"constant_gain_pull"' enables a constant-gain convex pull toward the selected-party structural vote-share path. 'structural_bridge_window' supplies one global inclusive calendar date range for both x-scale drift and bridge-specific sigma scaling. The bridge window is inclusive in calendar time; the bridge prior is applied to latent transitions after 'from' and through 'to'. The 'from' and 'to' dates must be exact latent anchor dates; use 'time_scale_overrides' when bridge endpoints need to be represented exactly on a coarser latent grid. Known states and zero-day steps are forced inactive. For '"x_drift"', 'from_x' and 'to_x' define the total drift size, 'to_x - from_x'; they are not an attractor endpoint. For example, if the sampled party vote share at the bridge start is 0.028 and 'from_x = 0.025', 'to_x = 0.043', the bridge adds 0.018, so absent innovations the drift points toward 0.046, not 0.043. For '"constant_gain_pull"', 'from_x' and 'to_x' define the structural target path and 'structural_bridge_alpha_week' is the weekly gap-closing fraction. The derived 'structural_bridge_x_target_t' is a full latent-grid target path and may include target values on inactive rows such as the bridge origin; 'structural_bridge_active_t' determines where the bridge prior is applied. Sigma scaling must be strictly positive, applies only during active bridge steps, and scales eta coordinates, not vote-share points directly.
Example 'model8m10' bridge setup:
time_scale_overrides <- tibble::tibble(
from = as.Date("2026-06-04"),
to = as.Date("2026-09-13"),
time_scale = "day"
)
hyper_parameters <- list(
structural_bridge_window = c(
as.Date("2026-06-04"),
as.Date("2026-09-13")
),
structural_bridge_x_target_path = data.frame(
y = "L",
from_x = 0.025,
to_x = 0.043
),
structural_bridge_sigma_scale = c(
M = 1, L = 0.5, C = 1, KD = 1,
S = 1, V = 1, MP = 1, SD = 1
)
)
Create a [polls_data] object
polls_data(y, house, publish_date, start_date, end_date, n, poll_id = NULL) as.polls_data(x, ...) ## S3 method for class 'polls_data' x[i, keep_poll_id = TRUE, ...]polls_data(y, house, publish_date, start_date, end_date, n, poll_id = NULL) as.polls_data(x, ...) ## S3 method for class 'polls_data' x[i, keep_poll_id = TRUE, ...]
y |
a named [data.frame] with variables of interest to estimate over time. |
house |
a factor variable indicating polling house (of same length as rows in [y]) |
publish_date |
the date of when the poll was published |
start_date |
the start date of the data collection period of each poll |
end_date |
the end date of the data collection period of each poll |
n |
the (integer) sample size of each poll |
poll_id |
the id of each poll. Deafult is [row.names] of [y]. |
x |
an object to convert to a [polls_data] object. |
... |
further arguments to methods. |
i |
row in [polls_data] to select. |
keep_poll_id |
Should the [poll_id] |
data(swedish_polls_curated) pd <- polls_data(y = swedish_polls_curated[,3:11], house = swedish_polls_curated$Company, publish_date = swedish_polls_curated$PublDate, start_date = swedish_polls_curated$collectPeriodFrom, end_date = swedish_polls_curated$collectPeriodTo, n = swedish_polls_curated$n)data(swedish_polls_curated) pd <- polls_data(y = swedish_polls_curated[,3:11], house = swedish_polls_curated$Company, publish_date = swedish_polls_curated$PublDate, start_date = swedish_polls_curated$collectPeriodFrom, end_date = swedish_polls_curated$collectPeriodTo, n = swedish_polls_curated$n)
Reweights the weights based on function
polls_time_reweight(x, poll_ids, FUN, ...)polls_time_reweight(x, poll_ids, FUN, ...)
x |
a [polls_time_weights] to reweight. |
poll_ids |
a character vector with poll_ids to reweight. |
FUN |
function used to reweight |
... |
further arguments to [FUN]. |
The function [FUN] is used to compute the weights for integer values 0,...,T_i, where T_i is the length of the period for poll i. The values from poll is then normalized to sum to 1.
The function takes a [poll_of_polls] object and recomplie the code an the data
recompile_stanfit(x)recompile_stanfit(x)
x |
a [poll_of_polls] object |
a recompiled [stanfit] object based on the model and data of the [poll_of_polls] object
'refit_poll_of_polls()' reconstructs a call to [poll_of_polls()] from an existing [poll_of_polls] object. The public API mirrors the practical refit use case: optionally replace 'polls_data', optionally choose refit-specific settings such as 'backend', 'compile_args', 'cache_dir', and 'warm_start', and use '...' only for backend sampler arguments.
Backend sampler arguments inherit from 'x' and can be overridden or removed via '...'. Named 'NULL' values remove stored sampler arguments.
Warm starts are filled in automatically unless you override them in 'warm_start'. Omitted 'warm_start' elements are taken from the last draw and sampler state of 'x'. When 'polls_data' changes, reused warm-start values are validated against the refit model's parameter dimensions before sampling begins.
Structural model inputs other than 'polls_data' are always inherited from 'x'; use [poll_of_polls()] directly to change 'y', 'model', 'time_scale', 'time_scale_overrides', 'known_state', 'model_time_range', 'latent_time_ranges', 'hyper_parameters', or 'slow_scales'.
refit_poll_of_polls( x, polls_data = x$polls_data, backend = "cmdstanr", compile_args = x$compile_arguments, cache_dir = x$cache_dir, warm_start = list(), ... ) reestimate_poll_of_polls( x, polls_data = x$polls_data, backend = "cmdstanr", compile_args = x$compile_arguments, cache_dir = x$cache_dir, warm_start = list(), ... )refit_poll_of_polls( x, polls_data = x$polls_data, backend = "cmdstanr", compile_args = x$compile_arguments, cache_dir = x$cache_dir, warm_start = list(), ... ) reestimate_poll_of_polls( x, polls_data = x$polls_data, backend = "cmdstanr", compile_args = x$compile_arguments, cache_dir = x$cache_dir, warm_start = list(), ... )
x |
Existing [poll_of_polls] object to refit. |
polls_data |
a [polls_data] object. Defaults to 'x$polls_data'. |
backend |
Stan backend to use for the refit. Only 'backend = "cmdstanr"' is currently supported because RStan does not accept a supplied mass matrix. The argument remains explicit so a future version can extend backend support without changing the public API. |
compile_args |
additional arguments passed to [cmdstanr::cmdstan_model()] when 'backend = "cmdstanr"'. Defaults to 'x$compile_arguments'. |
cache_dir |
directory to cache model. Defaults to 'x$cache_dir'. |
warm_start |
A named list controlling warm-start initialization. Supported elements are 'init', 'init_mode', 'inv_metric', 'metric_type', and 'step_size'. Omitted elements use the automatic defaults extracted from 'x'. Set an element to 'NULL' to disable that default warm-start component. When supplied, 'init_mode' must be one of '"last"' or '"random"'. The default is '"last"', which reuses the final draw from each stored chain and therefore requires the refit to use the same number of chains as the stored fit. For example, 'warm_start = list(inv_metric = NULL)' reuses the last draw but does not reuse the inverse metric. |
... |
Named backend sampler arguments supplied to 'CmdStanModel$sample()'. For 'backend = "cmdstanr"', these keep their usual CmdStanR meaning. If arguments are omitted, they are inherited from the stored arguments in 'x'. Warm-start controls such as 'init', 'init_mode', 'inv_metric', 'metric_type', and 'step_size' must be supplied through 'warm_start', not '...'. |
A refitted [poll_of_polls] object.
Remove file extension
remove_file_extension(x)remove_file_extension(x)
x |
a string with a file name |
function for removing known states outside timeline
remove_known_states( psd, known_state, model_time_range = NULL, time_scale = "week" )remove_known_states( psd, known_state, model_time_range = NULL, time_scale = "week" )
psd |
[polls_data] |
known_state |
data.frame containg known result needs date (date of the known data) |
model_time_range |
time range of where model is active |
time_scale |
what scale is the data at |
'rerun_poll_of_polls()' is a backward-compatible wrapper around [refit_poll_of_polls()]. It uses the refit implementation but disables automatic warm-start reuse by default, so the rerun behaves like a plain re-estimation unless you call [refit_poll_of_polls()] directly.
All arguments in '...' are forwarded to [refit_poll_of_polls()] except 'warm_start', which is intentionally not supported here.
rerun_poll_of_polls(x, ...)rerun_poll_of_polls(x, ...)
x |
Existing [poll_of_polls] object to rerun. |
... |
Arguments forwarded to [refit_poll_of_polls()], such as 'polls_data', 'backend', 'compile_args', 'cache_dir', and backend sampler arguments. |
A rerun [poll_of_polls] object.
Extract more detailed diagnostic information
Rhat_is_above_m_by_parameter_block(x, m = 1.1) Rhat_is_above_m(x, m = 1.1) Rhat_is_NA_by_parameter_block(x) Rhat_is_NA(x)Rhat_is_above_m_by_parameter_block(x, m = 1.1) Rhat_is_above_m(x, m = 1.1) Rhat_is_NA_by_parameter_block(x) Rhat_is_NA(x)
x |
a [poll_of_polls] object |
m |
a limit to extract Rhat values above |
Sample a dependent variable based on the polls
sample_polls_y(x, true_ls, tl, week_start = 1L)sample_polls_y(x, true_ls, tl, week_start = 1L)
x |
a [polls_data] object |
true_ls |
a numeric vector of the length as the [time_line] |
tl |
a [time_line] object. |
week_start |
the integer day starting the week (1 = Monday, 7 = Sunday). |
The [y] is sampled based on the [time_weights] and the [true_ls].
Save a [poll_of_polls] object in stanpop's wrapped on-disk format. The file contains a small metadata wrapper around the original object so [load_pop()] can verify that the file was created by [save_pop()] rather than by a plain [base::saveRDS()] call. The same wrapped format is also used internally for cached objects created by [poll_of_polls()] when 'cache_dir' is not [NULL].
save_pop(x, file, compress = "xz", overwrite = FALSE)save_pop(x, file, compress = "xz", overwrite = FALSE)
x |
A [poll_of_polls] object. |
file |
Path to the output '.rds' file. |
compress |
Compression passed to [base::saveRDS()]. |
overwrite |
Should an existing file at 'file' be overwritten? |
Invisibly returns 'x'.
Construct a list of [time_range]s
setup_latent_time_ranges(x, y, mtr, check_dates = TRUE)setup_latent_time_ranges(x, y, mtr, check_dates = TRUE)
x |
a list with a character vector with either "from" or "to" |
y |
all categories as a chacrater vector |
mtr |
a model [time_range] that will be used as default |
check_dates |
assert that the dates of [x] is in the [mtr] interval |
Simulate [npolls] polls for a given latent series [x], where the time slace is defined by [time_scale] and starting from [start_date]. Polling periods are randomly sampled from a a [polls_data] object.
simulate_polls( x, pd, npolls, time_scale = "week", start_date = as.Date("2010-01-04") )simulate_polls( x, pd, npolls, time_scale = "week", start_date = as.Date("2010-01-04") )
x |
a latent series to simulate polls for. Either a numeric vector or a data.frame. |
pd |
a [polls_data] object to sample poll periods and sample sizes from. |
npolls |
The total number of polls to simulate |
time_scale |
The time_scale used, [day], [week], [month] or [year]. |
start_date |
The starting date for the polls. |
Spanish election data
spanish_electionsspanish_elections
A data frame with 6 elections, 2008-2019
Adds missing data through NA to stan data
stan_data_add_missing(stan_data)stan_data_add_missing(stan_data)
stan_data |
contatning $y which can include missing in the form of na |
Generate Stan Data from [polls_data] objects
stan_polls_data( x, y_name, model, time_scale = "week", time_scale_overrides = NULL, known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model2(x, y_name, time_scale = "week", model_time_range = NULL) stan_polls_data_model3(x, y_name, time_scale = "week", model_time_range = NULL) stan_polls_data_model5( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL ) stan_polls_data_model6( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL ) stan_polls_data_model6b( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL ) stan_polls_data_model7( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL ) stan_polls_data_model8a( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL ) stan_polls_data_model8a1( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL ) stan_polls_data_model8b( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model8c( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model8d( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL, model )stan_polls_data( x, y_name, model, time_scale = "week", time_scale_overrides = NULL, known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model2(x, y_name, time_scale = "week", model_time_range = NULL) stan_polls_data_model3(x, y_name, time_scale = "week", model_time_range = NULL) stan_polls_data_model5( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL ) stan_polls_data_model6( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL ) stan_polls_data_model6b( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL ) stan_polls_data_model7( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL ) stan_polls_data_model8a( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL ) stan_polls_data_model8a1( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL ) stan_polls_data_model8b( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model8c( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL ) stan_polls_data_model8d( x, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, hyper_parameters = NULL, slow_scales = NULL, model )
x |
a [polls_data] object |
y_name |
a character vector indicating y variables in polls object. |
model |
model to get data for. |
time_scale |
to use. |
time_scale_overrides |
a [data.frame] with columns [from], [to], and [time_scale] that override the default [time_scale] for inclusive date ranges in the latent state. The [from] and [to] bounds are inclusive and override ranges must not overlap. |
known_state |
known time points in the latent state |
model_time_range |
the time range to model (for example for extrapolation) |
latent_time_ranges |
the time range of the latent state |
hyper_parameters |
a list with hyper parameters supplied to the model. |
slow_scales |
a vector of [Date]s that indicate breaks (right-inclusive) for a slower moving time scale. Example: If only 2010-01-15 is used, all dates up to and including 2010-01-15, will have s=1, Dates after 2010-01-15 will have s=2. |
For 'model8m10', 'hyper_parameters' can include 'structural_bridge_type', 'structural_bridge_window', 'structural_bridge_x_target_path', 'structural_bridge_alpha_week', 'structural_bridge_sigma_scale', and 'structural_bridge_epsilon'. 'structural_bridge_type = 0' means no bridge, while 'structural_bridge_type = 1' or '"x_drift"' enables a state-dependent x-scale drift for selected parties. 'structural_bridge_type = 2' or '"constant_gain_pull"' enables a constant-gain convex pull toward the structural vote-share path for selected parties. 'structural_bridge_window' supplies one global inclusive calendar date range for both x-scale drift and bridge-specific sigma scaling. The high-level 'structural_bridge_x_target_path' data frame should contain 'y', 'from_x', and 'to_x'; party names are matched through 'y_name'. For '"x_drift"', 'from_x' and 'to_x' define the total x-scale drift size, 'to_x - from_x', which is allocated over active bridge steps in proportion to 'delta_days_t'. They are not an attractor endpoint. For example, if the sampled party vote share at the bridge start is 0.028 and 'from_x = 0.025', 'to_x = 0.043', the bridge adds 0.018, so absent innovations the drift points toward 0.046, not 0.043. For '"constant_gain_pull"', 'from_x' and 'to_x' define the selected-party structural target path, and 'structural_bridge_alpha_week' is the weekly gap-closing fraction. A half-life of 'H' days corresponds to '1 - 2^(-7 / H)'. The derived low-level 'structural_bridge_x_target_t' is a full target-path matrix on the latent time grid. It can contain target values at rows where 'structural_bridge_active_t == 0', especially the bridge origin. 'structural_bridge_active_t' is the source of truth for where the bridge prior is applied in the state equation. Since the state transition is from 't - 1' into 't', the bridge origin usually has 'active_t = 0', while dates after the origin and up to the target date have 'active_t = 1'. For example:
date active_t x_target_t[L] 2026-06-08 0 0.026 2026-06-09 1 0.0262 ... 2026-09-13 1 0.044
The bridge window is inclusive in calendar time; the bridge prior is applied to latent transitions after 'from' and through 'to'. The 'from' and 'to' dates must be exact latent anchor dates in 'time_line$time_line$date'; use 'time_scale_overrides' when bridge endpoints need to be represented exactly on a coarser latent grid. Known states and zero-day steps are forced inactive. 'structural_bridge_sigma_scale' is ordered by 'y_name' when named, must be strictly positive, applies only during active bridge steps, and scales eta-coordinate innovations rather than vote-share points directly.
Example 'model8m10' bridge setup:
time_scale_overrides <- tibble::tibble(
from = as.Date("2026-06-04"),
to = as.Date("2026-09-13"),
time_scale = "day"
)
hyper_parameters <- list(
structural_bridge_window = c(
as.Date("2026-06-04"),
as.Date("2026-09-13")
),
structural_bridge_x_target_path = data.frame(
y = "L",
from_x = 0.025,
to_x = 0.043
),
structural_bridge_sigma_scale = c(
M = 1, L = 0.5, C = 1, KD = 1,
S = 1, V = 1, MP = 1, SD = 1
)
)
The returned object keeps the existing [stan_data] and [time_line] fields unchanged for current models. A parallel future path is attached in [stan_data_with_overrides] and [time_line_with_overrides], built using [time_line_with_overrides()].
Compute the posterior predictive distribution of polls
stan_polls_data_model( spd, psd, y_name, time_scale, known_state, model_time_range, latent_time_ranges, ... ) ## S3 method for class 'model2' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model3' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model4' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model5' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model6' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model6b' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model6c' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model7' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model9' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... )stan_polls_data_model( spd, psd, y_name, time_scale, known_state, model_time_range, latent_time_ranges, ... ) ## S3 method for class 'model2' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model3' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model4' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model5' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model6' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, ... ) ## S3 method for class 'model6b' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model6c' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model7' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... ) ## S3 method for class 'model9' stan_polls_data_model( spd, psd, y_name, time_scale = "week", known_state = NULL, model_time_range = NULL, latent_time_ranges = NULL, ... )
spd |
a [stan_polls] objects |
psd |
a [poll_of_polls] object |
y_name |
names of interested parties |
time_scale |
one what scale is the data |
known_state |
states where we know the data exactly |
model_time_range |
what is the time range where the model is active |
latent_time_ranges |
not certain |
... |
extra arguments |
Compute standard errors for poll estimates
standard_error(x, y, type = "binomial")standard_error(x, y, type = "binomial")
x |
a [polls_data] object |
y |
variable to compute standrad error for |
type |
type of standard error estimator |
A package to run poll of polls models and Bayesian election prediction models
Maintainer: Mans Magnusson [email protected]
Subset a latent state based on a time range
subset_latent_state_dates(x, from = NULL, to = NULL, ...) subset_time_line_dates(x, from = NULL, to = NULL, ...)subset_latent_state_dates(x, from = NULL, to = NULL, ...) subset_time_line_dates(x, from = NULL, to = NULL, ...)
x |
a [latent_state] object |
from |
subset from [date] |
to |
subset to [date] |
... |
Currently not in use. |
Subset a [polls_data] object. * [subset_publish_dates()] subset the data with the polls that has a publication date within the interval. * [subset_dates()] subset the data with the polls that has all non-[NA] dates in the interval.
subset_publish_dates(x, from = NULL, to = NULL, ...) subset_dates(x, from = NULL, to = NULL, ...)subset_publish_dates(x, from = NULL, to = NULL, ...) subset_dates(x, from = NULL, to = NULL, ...)
x |
a [polls_data] object |
from |
a the earliest date to include polls for |
to |
a the latest date to include polls for |
... |
further arguments |
Subset a [polls_data] object.
## S3 method for class 'polls_data' subset(x, subset, select, drop = FALSE, ...)## S3 method for class 'polls_data' subset(x, subset, select, drop = FALSE, ...)
x |
a [polls_data] |
subset, select, drop, ...
|
see [subset()] |
Summarize a polls weight object by a time line
summarize_polls_time_weights(ptw, tl)summarize_polls_time_weights(ptw, tl)
ptw |
a [polls_time_weights] object. |
tl |
a [time_line] object. |
a [polls_time_weights] object.
Swedish election data
swedish_electionsswedish_elections
A data frame with 4 elections, 2006-2018
Party time ranges
swedish_party_time_ranges german_party_time_ranges spanish_party_time_rangesswedish_party_time_ranges german_party_time_ranges spanish_party_time_ranges
A named list (parties) with starting and ending dates.
An object of class list of length 1.
An object of class list of length 2.
Time ranges for political parties
Swedish polls data
swedish_pollsswedish_polls
A data frame with 1565 polls and 9 parties:
http://www.github.com/MansMeg/SwedishPolls
Spanish polls data
swedish_polls_curated spanish_polls spanish_polls_curatedswedish_polls_curated spanish_polls spanish_polls_curated
An object of class tbl_df (inherits from tbl, data.frame) with 1660 rows and 18 columns.
A data frame with 1852 polls and 7 parties:
An object of class data.frame with 1345 rows and 16 columns.
Construct a timeline to use based on the [time_scale] of interest.
time_line( x, time_scale, ..., week_start = getOption("lubridate.week.start", 1) ) ## S3 method for class 'numeric' time_line( x, time_scale, start_date, ..., week_start = getOption("lubridate.week.start", 1) ) ## S3 method for class 'data.frame' time_line( x, time_scale, start_date, ..., week_start = getOption("lubridate.week.start", 1) )time_line( x, time_scale, ..., week_start = getOption("lubridate.week.start", 1) ) ## S3 method for class 'numeric' time_line( x, time_scale, start_date, ..., week_start = getOption("lubridate.week.start", 1) ) ## S3 method for class 'data.frame' time_line( x, time_scale, start_date, ..., week_start = getOption("lubridate.week.start", 1) )
x |
a vector of the same length as the [time_line], a [polls_data] object, or a [time_range] object. |
time_scale |
The time_scale, [day], [week] or [month]. |
... |
Further arguments to methods. |
week_start |
What is week starting day (1 = Monday, Default or 7 = Sunday). |
start_date |
The starting date of the [time_line]. |
The timeline is created based on full months, week or days. If a [start_date] is supplied, length(x) no of days/weeks/months units are added, including the day/week/month of [start_date]. Hence, the number of total days of the [time_line] will change, based on the weekday of [start_date].
If [time_range] is supplied, the [time_line] will include every day/week/month that overlaps the closed interval defined by [time_range], including partial periods at both boundaries.
a [time_line] object. A list with two data frames, one for a [daily] [time_line] and one with the [time_line] for the chosen [time_scale]. Both [data.frames] consist of a [date] variable and a [t] index column.
Rebuild a [time_line] on a larger [time_range] while shifting the new daily and latent indices so that dates already present in [tl] keep the same [t] and [time_line_t] values as before.
time_line_expand(tl, time_range)time_line_expand(tl, time_range)
tl |
a time_line to expand |
time_range |
a new time range to expand to |
Time range
time_range(x, ...) time_range(x) <- value time_range_polls(x, ...)time_range(x, ...) time_range(x) <- value time_range_polls(x, ...)
x |
an object to compute the time range for. |
... |
further arguments supplied to method. |
value |
a Date vector of length 2 with names [from] and [to]. |
Compute the time range for an object with [time_range] or compute the time range of the polls in the object with [time_range_polls].
Check if two time ranges are disjoint (not overlapping)
time_ranges_are_disjoint(tr1, tr2)time_ranges_are_disjoint(tr1, tr2)
tr1 |
first [time_range] |
tr2 |
second [time_range] |
Convert each date in [x] to the start date of its corresponding [time_scale] bucket/latent slot. For example, dates can be mapped to the same week start or month start when constructing a latent time line.
time_scale_dates( x, time_scale, week_start = getOption("lubridate.week.start", 1) )time_scale_dates( x, time_scale, week_start = getOption("lubridate.week.start", 1) )
x |
a vector of dates to convert to a specific [time_scale] |
time_scale |
to use. |
week_start |
Day on which week starts following ISO conventions - 1 means Monday (default), 7 means Sunday. You can set lubridate.week.start option to control this parameter globally. |
Checks sampler arguments before a backend fit starts. This rejects common argument names from the other Stan backend so callers supply arguments in the style expected by the selected backend.
validate_backend_sample_arguments(backend, sample_arguments)validate_backend_sample_arguments(backend, sample_arguments)
backend |
Stan backend to validate against. Supported values are [rstan] and [cmdstanr]. |
sample_arguments |
A list of arguments intended for the backend sampler. |
Invisibly returns 'TRUE' when validation succeeds.
Compute the posterior predictive distribution of polls
x_predict(x, y = NULL, t = NULL, ...) ## S3 method for class 'pop_model6b' x_predict(x, y = NULL, t = NULL, ...) ## S3 method for class 'pop_model6c' x_predict(x, y = NULL, t = NULL, ...)x_predict(x, y = NULL, t = NULL, ...) ## S3 method for class 'pop_model6b' x_predict(x, y = NULL, t = NULL, ...) ## S3 method for class 'pop_model6c' x_predict(x, y = NULL, t = NULL, ...)
x |
a [poll_of_polls] object |
y |
a vector of categories to compute the predicted distribution for |
t |
a vector of time points to compute the predictive for for the latent state. If [NULL], the whole latent state is returned. If [t] exist in latent state, the latent state is returned. |
... |
Currently not in use. |
Four true latent states used in experiments
x_testx_test
A list of length four with numeric vectors of length 100.
See data-raw folder for exact construction.
Compute the posterior predictive distribution of polls
y_predict(x, y = NULL, poll_ids = NULL, ...) poll_predictive_distribution(x, y = NULL, poll_ids = NULL, ...) ## S3 method for class 'pop_model6b' y_predict(x, y = NULL, poll_ids = NULL, ...) ## S3 method for class 'pop_model6c' y_predict(x, y = NULL, poll_ids = NULL, ...)y_predict(x, y = NULL, poll_ids = NULL, ...) poll_predictive_distribution(x, y = NULL, poll_ids = NULL, ...) ## S3 method for class 'pop_model6b' y_predict(x, y = NULL, poll_ids = NULL, ...) ## S3 method for class 'pop_model6c' y_predict(x, y = NULL, poll_ids = NULL, ...)
x |
a [poll_of_polls] object |
y |
a vector of categories to compute the predicted distribution for |
poll_ids |
a vector of poll ids to compute the predictive for. If [NULL] all are computed. |
... |
Currently not used. |