R/sprinkle_discrete.R

Defines functions sprinkle_discrete_index sprinkle_discrete_index_assert sprinkle_discrete.dust_list sprinkle_discrete.default sprinkle_discrete

Documented in sprinkle_discrete sprinkle_discrete.default sprinkle_discrete.dust_list

#' @name sprinkle_discrete
#' @title Change Color Features by Discrete Values
#' 
#' @description Distinct values within a range will be assigned a color and
#'   the designated attribute of the table will be modified accordingly.
#'   
#' @param x An object of class \code{dust}
#' @param rows Either a numeric vector of rows in the tabular object to be 
#'   modified or an object of class \code{call}.  When a \code{call}, 
#'   generated by \code{quote(expression)}, the expression resolves to 
#'   a logical vector the same length as the number of rows in the table.
#'   Sprinkles are applied to where the expression resolves to \code{TRUE}.
#' @param cols Either a numeric vector of columns in the tabular object to
#'   be modified, or a character vector of column names. A mixture of 
#'   character and numeric indices is permissible.
#' @param discrete \code{character}. A subset of \code{c("bg", "font", 
#'   "font_color", "border", "left_border", "top_border", "right_border",
#'   "bottom_border")}.
#' @param discrete_colors \code{character}. Gives the color palette to be 
#'   used. Each value must be a valid color.  Defaults to evenly spaced
#'   colors over the color space.
#' @param part A character string denoting which part of the table to modify.
#' @param fixed \code{logical(1)} indicating if the values in \code{rows} 
#'   and \code{cols} should be read as fixed coordinate pairs.  By default, 
#'   sprinkles are applied at the intersection of \code{rows} and \code{cols}, 
#'   meaning that the arguments do not have to share the same length.  
#'   When \code{fixed = TRUE}, they must share the same length.
#' @param recycle A \code{character} one that determines how sprinkles are 
#'   managed when the sprinkle input doesn't match the length of the region
#'   to be sprinkled.  By default, recycling is turned off.  Recycling 
#'   may be performed across rows first (left to right, top to bottom), 
#'   or down columns first (top to bottom, left to right).
#' @param ... Additional arguments to pass to other methods. Currently ignored.
#' 
#' @details This sprinkle is only recognized by HTML and LaTeX.  All of the 
#'   \code{height_units} values are recognized by HTML.  For LaTeX, \code{"px"}
#'   is converted to \code{"pt"}. 
#'   
#' \code{"font"} and \code{"font_color"} both change the font color.
#' 
#' \code{"border"} is a shortcut to specify all borders.
#'   
#' @section Functional Requirements:
#' \enumerate{
#'  \item Correctly reassigns the appropriate elements of the \code{bg},
#'    \code{font_color}, \code{left_border}, \code{top_border},
#'    \code{right_border}, or \code{bottom_border} column in the table part.
#'  \item Casts an error if \code{x} is not a \code{dust} object.
#'  \item Casts an error if \code{discrete} is not a subset of 
#'    \code{c("bg", "font", "font_color", "border", "left_border",
#'            "right_border", "top_border", "bottom_border")}
#'  \item Casts an error if \code{discrete_colors} is not a \code{character}
#'    value.
#'  \item Casts an error if any value of \code{discrete_colors} is not a
#'    recognized color value.
#'  \item Casts an error if \code{part} is not one of \code{"body"}, 
#'    \code{"head"}, \code{"foot"}, or \code{"interfoot"}
#'  \item Casts an error if \code{fixed} is not a \code{logical(1)}
#'  \item Casts an error if \code{recycle} is not one of \code{"none"},
#'    \code{"rows"}, or \code{"cols"}
#' }
#' 
#' The functional behavior of the \code{fixed} and \code{recycle} arguments 
#' is not tested for this function. It is tested and validated in the
#' tests for \code{\link{index_to_sprinkle}}.
#' 
#' @seealso \code{\link{sprinkle}}, 
#'   \code{\link{index_to_sprinkle}}
#'   
#' @export

sprinkle_discrete <- function(x, rows = NULL, cols = NULL, 
                              discrete = "bg",
                              discrete_colors = getOption("pixie_discrete_pal", NULL),
                              part = c("body", "head", "foot", "interfoot", "table"),
                              fixed = FALSE, 
                              recycle = c("none", "rows", "cols", "columns"),
                            ...)
{
  UseMethod("sprinkle_discrete")
}

#' @rdname sprinkle_discrete
#' @export

sprinkle_discrete.default <- function(x, rows = NULL, cols = NULL, 
                                   discrete = "bg",
                                   discrete_colors = getOption("pixie_discrete_pal", NULL),
                                   part = c("body", "head", "foot", "interfoot", "table"),
                                   fixed = FALSE, 
                                   recycle = c("none", "rows", "cols", "columns"),
                                   ...)
{
  coll <- checkmate::makeAssertCollection()
  
  checkmate::assert_class(x = x,
                          classes = "dust",
                          add = coll)
  
  sprinkle_discrete_index_assert(discrete = discrete,
                                 discrete_colors = discrete_colors,
                                 coll = coll) 
  
  indices <- index_to_sprinkle(x = x, 
                               rows = rows, 
                               cols = cols, 
                               fixed = fixed,
                               part = part,
                               recycle = recycle,
                               coll = coll)
  
  checkmate::reportAssertions(coll)
  
  sprinkle_discrete_index(x = x, 
                          indices = indices, 
                          discrete = discrete, 
                          discrete_colors = discrete_colors, 
                          part = part)
}

#' @rdname sprinkle_discrete
#' @export

sprinkle_discrete.dust_list <- function(x, rows = NULL, cols = NULL, 
                                        discrete = "bg",
                                        discrete_colors = getOption("pixie_discrete_pal", NULL),
                                      part = c("body", "head", "foot", "interfoot", "table"),
                                      fixed = FALSE, 
                                      recycle = c("none", "rows", "cols", "columns"),
                                      ...)
{
  structure(
    lapply(X = x,
           FUN = sprinkle_discrete.default,
           rows = rows,
           cols = cols,
           discrete = discrete,
           discrete_colors = discrete_colors,
           part = part,
           fixed = fixed,
           recycle = recycle,
           ...),
    class = "dust_list"
  )
}

# Unexported Utility ------------------------------------------------

# These functions are to be used inside of the general `sprinkle` call
# When used inside `sprinkle`, the indices are already determined, 
# the only the `height` and `height_units` arguments needs to be validated. 
# The assert function is kept separate so it may be called earlier
# without attempting to perform the assignment.

sprinkle_discrete_index_assert <- function(discrete = "bg", 
                                           discrete_colors = getOption("pixie_discrete_pal", NULL), 
                                           coll)
{
  checkmate::assert_subset(x = discrete,
                           choices = c("bg", "font", "font_color",
                                       "border", "left_border", 
                                       "top_border", "right_border",
                                       "bottom_border"),
                           add = coll)
  
  if (!is.null(discrete_colors))
  {
    checkmate::assert_character(x = discrete_colors,
                                add = coll)
    
    valid_color <- is_valid_color(discrete_colors)  
    if (!all(valid_color))
    {
      coll$push(sprintf("The following are not valid colors: %s",
                        paste0(discrete_colors[!valid_color], 
                               collapse = ", ")))
    }
  }  
}

sprinkle_discrete_index <- function(x, indices, 
                                    discrete = "bg", 
                                    discrete_colors = getOption("pixie_discrete_pal", NULL), 
                                    part,
                                    ...)
{
  part <- part[1]
  
  if ("border" %in% discrete)
  {
    discrete <- c(sprintf("%s_border", 
                          c("top", "left", "right", "bottom")),
                  discrete)
    discrete <- unique(discrete[!discrete %in% "border"])
  }
  
  if ("font" %in% discrete)
  {
    discrete <- c("font_color", discrete)
    discrete <- unique(discrete[!discrete %in% "font"])
  }
  
  ux <- unique(x[[part]][["value"]][indices])
  
  if (is.null(discrete_colors)) 
  {
    discrete_colors <- getOption("pixie_discrete_pal", NULL)
  }
  
  if (is.null(discrete_colors))
  {
    discrete_colors <- scales::hue_pal()(length(ux))
  }
  
  checkmate::makeAssertion(x = discrete_colors,
                           if (length(discrete_colors) >= length(ux))
                           {
                             TRUE
                           }
                           else
                           {
                             sprintf("`discrete_colors` must have at least the same length as the number of unique values (>= %s)",
                                     length(ux))
                           },
                           var.name = "discrete_colors",
                           collection = NULL)
  
  args <- list(...)
  
  border_thickness <- 
    if ("border_thickness" %in% names(args)) args[["border_thickness"]] else 1
  
  border_units <- 
    if ("border_units" %in% names(args)) args[["border_units"]] else "px"
  
  border_style <- 
    if ("border_style" %in% names(args)) args[["border_style"]] else "solid"
  
  for (i in seq_along(discrete))
  {
    if (grepl("border", discrete[i]))
    {
      x[[part]][[discrete[i]]][indices] <- 
        sprintf("%s%s %s %s",
                border_thickness,
                border_units,
                border_style,
                discrete_colors[as.numeric(as.factor(x[[part]][["value"]][indices]))])
    }
    else 
    {
      x[[part]][[discrete[i]]][indices] <- 
        discrete_colors[as.numeric(as.factor(x[[part]][["value"]][indices]))]
    }
  }
  
  x
}

Try the pixiedust package in your browser

Any scripts or data that you put into this service are public.

pixiedust documentation built on Oct. 10, 2023, 9:07 a.m.