Debian Codegraph @

inst/examples/04_mpg/app.R

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