R/plot_rdf_estimates_by_choice.R

Defines functions plot_rdf_estimates_by_choice

Documented in plot_rdf_estimates_by_choice

#' Plot Estimates by Choice
#'
#' Visualizes the variance of estimates conditional on a selected
#' discrete and continous choice.
#'
#' @param df The data frame as generated by \code{exhaust_design()}.
#' @param est A character value to indicate the variable in \code{df} that contains the pont estimate
#'   that you want to plot.
#' @param lb A character value indicating the variable in \code{df} that contains
#'   the lower bound of the estimate.
#' @param ub A character value indicating the variable in \code{df} that contains
#'   the upper bound of the estimate.
#' @param dchoice A character value to indicate the discrete choice that you want to partition
#'   your estimates on.
#' @param color A character value to indicate a choice for the coloring of the
#'   point ranges. Can be continous or discrete.
#' @param order A character value to indicate a choice for ordering the
#'   point ranges. If \code{NULL} (the default), the point ranges will be ordered by estimate magnitude.
#' @param width The \code{width} parameter for \code{\link[ggplot2]{position_dodge2}}
#'   to spread out the point ranges within the discrete choice area.
#' @return A \code{ggplot} object containing the plot.
#' @details See the vignette of the package for further details on how to implement the RDF workflow.
#' @examples
#' \dontrun{
#'   print("Sorry. No examples yet.")
#' }
#' @export

plot_rdf_estimates_by_choice <- function(df, est, lb, ub,
                                         dchoice, color = NULL,
                                         order = NULL,
                                         width = 1) {
  if (is.null(order)) df <- df %>% dplyr::arrange_(dchoice, est)
  else df <- df %>% dplyr::arrange_(dchoice, order, est)

  if (is.null(order)) x <- est else x <- order

  if (is.null(color)) {
    p <- ggplot2::ggplot(df, ggplot2::aes_string(x = x)) +
      ggplot2::facet_grid(stats::as.formula(paste("~", dchoice)), scales="free_x", switch = "x") +
      ggplot2::geom_pointrange(ggplot2::aes_string(y = est, ymin = lb, ymax = ub)) +
      ggplot2::theme_minimal() +
      ggplot2::theme(strip.placement = "outside") +
      ggplot2::xlab("Discrete Choices") +
      ggplot2::ylab("Estimate and confidence interval")
  } else {
    p <- ggplot2::ggplot(df, ggplot2::aes_string(x = x, color = color)) +
      ggplot2::facet_grid(stats::as.formula(paste("~", dchoice)), scales="free_x", switch = "x") +
      ggplot2::geom_pointrange(ggplot2::aes_string(y = est, ymin = lb, ymax = ub),
                               position = ggplot2::position_dodge2(width = width)) +
      ggplot2::theme_minimal() +
      ggplot2::theme(strip.placement = "outside") +
      ggplot2::xlab("Discrete Choices") +
      ggplot2::ylab("Estimate and confidence interval")
  }
  p
}
joachim-gassen/rdfanalysis documentation built on Aug. 22, 2023, 5:29 p.m.