TIL: Week 11 In-Class Exercise

Today I learnt in class: How to build a R Shiny app.

Kelly Koh https://www.linkedin.com/in/kellykkw/ (School of Computing and Information Systems, Singapore Management University)https://scis.smu.edu.sg/
07-17-2021

Set Up a R Shiny App

library(shiny)
library(tidyverse)

exam <- read_csv("data/Exam_data.csv")

# Define UI for application 
ui <- fluidPage(
    titlePanel("Pupils Examination Results Dashboard"),
    sidebarLayout(
        sidebarPanel(
            selectInput(inputId = "variable",
                        label = "Subject: ",
                        choices = c("English" = "ENGLISH", 
                                    "Math" = "MATHS", 
                                    "Science" = "SCIENCE"),
                        selected = "ENGLISH"),
            sliderInput(inputId = "bin",
                        label = "Number of bins",
                        min = 5,
                        max = 20,
                        value = c(10)),
            checkboxInput(inputId = "show_data",
                          label = "Show data table",
                          value = TRUE)
        ),
        mainPanel(
            plotOutput("distplot"),
            DT::dataTableOutput(outputId = "examtable")
        )
    )
)

# Define server logic 
server <- function(input, output) {
    output$distplot <- renderPlot({
        x <- unlist(exam[,input$variable])
        ggplot(exam, aes(x)) +
            geom_histogram(bins = input$bin,
                           color = "black",
                           fill = "light blue")
    })
    
    output$examtable <- DT::renderDataTable({
        if(input$show_data){
            DT::datatable(data = exam %>%
                          select(1:7),
                          options = list(pageLength = 10),
                          rownames = FALSE)
        }
    })
}

# Run the application 
shinyApp(ui = ui, server = server)