| 1 |
library(shiny) |
| 2 |
library(bslib) |
| 3 |
library(datasets) |
| 4 |
|
| 5 |
# Data pre-processing ---- |
| 6 |
# Tweak the "am" variable to have nicer factor labels -- since this |
| 7 |
# doesn't rely on any user inputs, we can do this once at startup |
| 8 |
# and then use the value throughout the lifetime of the app |
| 9 |
mpgData <- mtcars |
| 10 |
mpgData$am <- factor(mpgData$am, labels = c("Automatic", "Manual")) |
| 11 |
|
| 12 |
|
| 13 |
# Define UI for miles per gallon app ---- |
| 14 |
ui <- page_sidebar( |
| 15 |
|
| 16 |
# App title ---- |
| 17 |
title = "Miles Per Gallon", |
| 18 |
|
| 19 |
# Sidebar panel for inputs ---- |
| 20 |
sidebar = sidebar( |
| 21 |
|
| 22 |
# Input: Selector for variable to plot against mpg ---- |
| 23 |
selectInput( |
| 24 |
"variable", |
| 25 |
"Variable:", |
| 26 |
c( |
| 27 |
"Cylinders" = "cyl", |
| 28 |
"Transmission" = "am", |
| 29 |
"Gears" = "gear" |
| 30 |
) |
| 31 |
), |
| 32 |
|
| 33 |
# Input: Checkbox for whether outliers should be included ---- |
| 34 |
checkboxInput("outliers", "Show outliers", TRUE) |
| 35 |
), |
| 36 |
|
| 37 |
# Output: Formatted text for caption ---- |
| 38 |
h3(textOutput("caption")), |
| 39 |
|
| 40 |
# Output: Plot of the requested variable against mpg ---- |
| 41 |
plotOutput("mpgPlot") |
| 42 |
) |
| 43 |
|
| 44 |
# Define server logic to plot various variables against mpg ---- |
| 45 |
server <- function(input, output) { |
| 46 |
|
| 47 |
# Compute the formula text ---- |
| 48 |
# This is in a reactive expression since it is shared by the |
| 49 |
# output$caption and output$mpgPlot functions |
| 50 |
formulaText <- reactive({ |
| 51 |
paste("mpg ~", input$variable) |
| 52 |
}) |
| 53 |
|
| 54 |
# Return the formula text for printing as a caption ---- |
| 55 |
output$caption <- renderText({ |
| 56 |
formulaText() |
| 57 |
}) |
| 58 |
|
| 59 |
# Generate a plot of the requested variable against mpg ---- |
| 60 |
# and only exclude outliers if requested |
| 61 |
output$mpgPlot <- renderPlot({ |
| 62 |
boxplot( |
| 63 |
as.formula(formulaText()), |
| 64 |
data = mpgData, |
| 65 |
outline = input$outliers, |
| 66 |
col = "#75AADB", |
| 67 |
pch = 19 |
| 68 |
) |
| 69 |
}) |
| 70 |
} |
| 71 |
|
| 72 |
# Create Shiny app ---- |
| 73 |
shinyApp(ui, server) |