R/dcpo.R

Defines functions dcpo

Documented in dcpo

#' Estimate Dynamic Comparative Public Opinion
#'
#' \code{dcpo} uses diverse survey data to estimate public opinion across countries and over time.
#'
#' @param dcpo_input a data frame of survey items and marginals generated by \code{DCPOtools::dcpo_setup}
#' @param chime play chime when complete?
#' @param ... arguments to be passed to \code{rstan::stan}. Defaults reset by \code{dcpo} are
#' described below under details.
#
#' @details \code{dcpo}, when passed a data frame \code{dcpo_input} of survey marginals created
#' by \code{dcpo_setup}, estimates a latent variable of public opinion.  See \code{rstan::stan} for
#' additional options; \code{stan} defaults reset by \code{dcpo} are \code{seed = 324, thin = 2,}
#' \code{cores = min(stan_args$chains, parallel::detectCores()/2),} and \code{control <- list(adapt_delta = 0.99, stepsize = 0.005, max_treedepth = 14)}
#' @examples
#' \donttest{
#' out1 <- dcpo(demsup_data,
#'              chains = 1,
#'              iter = 300) # 1 chain/300 iterations for example purposes only; use defaults
#' }
#'
#' @return a stanfit object
#'
#' @import rstan
#' @importFrom beepr beep
#'
#' @export

dcpo <- function(dcpo_input,
                 chime = TRUE,
                 ...) {

  dcpo_model <- stanmodels$dcpo
  stan_args <- list(object = dcpo_model,
                    data = dcpo_input,
                    ...)
  if (!length(stan_args$control)) {
    stan_args$control <- list(adapt_delta = 0.99, stepsize = 0.005, max_treedepth = 14)
  }
  if (!length(stan_args$seed)) {
    stan_args$seed <- 324
  }
  if (!length(stan_args$thin)) {
    stan_args$thin <- 2
  }
  if (!length(stan_args$cores)) {
    stan_args$cores <- min(stan_args$chains, parallel::detectCores()/2)
  }
  out1 <- do.call(rstan::sampling, stan_args)

  # Chime
  if(chime) {
    try(beep())
  }

  return(out1)
}
fsolt/DCPO documentation built on Oct. 1, 2023, 9:44 p.m.