18.2 UI Functions

Functions are useful in reducing duplication

CASE 1: converting multiple sliders to a function

ui <- fluidRow(
  sliderInput("alpha", "alpha", min = 0, max = 1, value = 0.5, step = 0.1),
  sliderInput("beta",  "beta",  min = 0, max = 1, value = 0.5, step = 0.1),
  sliderInput("gamma", "gamma", min = 0, max = 1, value = 0.5, step = 0.1),
  sliderInput("delta", "delta", min = 0, max = 1, value = 0.5, step = 0.1)
)

TO:

sliderInput01 <- function(id) {
  sliderInput(id, label = id, min = 0, max = 1, value = 0.5, step = 0.1)
}

ui <- fluidRow(
  sliderInput01("alpha"),
  sliderInput01("beta"),
  sliderInput01("gamma"),
  sliderInput01("delta")
)

Like functions in R analyses, functions in apps makes you app more readable and efficient if we need to change the behavior, we would only do it one place.

CASE 2: customized dateInput with ...

usWeekDateInput <- function(inputId, ...) {
  dateInput(inputId, ..., format = "dd M, yy", daysofweekdisabled = c(0, 6))
}

Just a reminder on dateInput:

dateInput(
  inputId,
  label,
  value = NULL,
  min = NULL,
  max = NULL,
  format = "yyyy-mm-dd",
  startview = "month",
  weekstart = 0,
  language = "en",
  width = NULL,
  autoclose = TRUE,
  datesdisabled = NULL,
  daysofweekdisabled = NULL
)

CASE 3: radio buttons to make

iconRadioButtons <- function(inputId, label, choices, selected = NULL) {
  names <- lapply(choices, icon)
  values <- if (is.null(names(choices))) names(choices) else choices
  radioButtons(inputId,
               label = label,
               choiceNames = names, choiceValues = values, selected = selected
  )
}

18.2.1 Functional Programming

  • Using functions like map() may help reduce code further
library(purrr)
# pass the variables for the slider to the built function sliderInput01
vars <- c("alpha", "beta", "gamma", "delta")
# returns a list of sliders
sliders <- map(vars, sliderInput01)
# fluidRow unpacks the list to become children of the container
ui <- fluidRow(sliders)

18.2.2 UI as data

Turning a UI structure into a data structure to have more varitey in inputs

vars <- tibble::tribble(
  ~ id,   ~ min, ~ max,
  "alpha",     0,     1,
  "beta",      0,    10,
  "gamma",    -1,     1,
  "delta",     0,     1,
)

# function where arg names match the col names

mySliderInput <- function(id, label = id, min = 0, max = 1) {
  sliderInput(id, label, min = min, max = max, value = 0.5, step = 0.1)
}

# pmap to call mySliderInput over vars

sliders <- pmap(vars, mySliderInput)