Lab 4 Shiny App Lab

Question 1

The below code sets up a data frame, df that you will use in order to create a shiny app that compares the t distribution to the Z distribution at different levels of degrees of freedom (n-1). Your n term will be the input value for your shiny app.

library(shiny)
## Warning: package 'shiny' was built under R version 4.5.2
library(ggplot2)
# x <- seq(-4, 4, by=0.01)
# norm_dens <- dnorm(x)
# t_dens <- dt(x, df = n-1)
# df = data.frame(x = x, z = norm_dens, t = t_dens)

Write your code for the shiny app below. I’ve set up the UI, Server, and Run steps. You will fill in the details so that when you run the user interface and server logic together, the output will include:

  • Static standard Normal distribution curve in blue using ggplot geom_line()

  • Dynamic t distribution curve that is dependent on degrees of freedom (n-1) in red using ggplot geom_line()

  • A slider input that determines the sample size from minimum value of 2 (since df can be no less than 1) to maximum value of 100, stepping by 1

## UI function
ui <- fluidPage(
  
  sliderInput("num", label = "n", value = 2, min = 2, max = 100, step = 1),
  plotOutput("dynamic")
)

# Server logic
server <- function(input, output) {
  output$dynamic <- renderPlot({
    x <- seq(-4, 4, by=0.01)
    norm_dens <- dnorm(x)
    max1 = max(norm_dens)
    t_dens <- dt(x, df = input$num - 1)
    
    df = data.frame(x = x, z = norm_dens, t = t_dens)
    
    ggplot(df) + 
      geom_line(aes(x = x, y = z), color = "blue") + 
      geom_line(aes(x = x, y = t), color = "red") + 
      xlim(-4,4) + 
      ylim(0, 1.25 * max1) 
  }, res = 96)
}

## Run shiny app
shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents

Question 2

Using the iris data set, create a scatterplot using the shiny app. The graph should include some interactive capability to select which variables to compare on the x and y axes.

## UI Function 
library(shiny) 
ui <- fluidPage(
  fluidRow(
    column(5,
      p("Select Data", style = "font-size: 32px;"))
    ),
    fluidRow(
    column(2,
  selectInput("x", "x-axis data", names(iris)),
    ),
    column(2,
  selectInput("y", "y-axis data", names(iris)),
  )),
  fluidRow(
    column(4, 
    p("From Zero View", style = "font-size: 24px;"),
  plotOutput("Iris", height = "125px", width = "125px"),
  )),
  fluidRow(
    column(2,
    p("Fit View", style = "font-size: 24px;"),
  plotOutput("iris", height = "400px", width = "400px")
  )))

## Server logic
server <- shinyServer(function(input, output) {   
  output$Iris <- renderPlot({
    ggplot(iris, aes_string(x = input$x, y = input$y)) +
      geom_point(size = 0.1) +
      xlim(0,NA) +
      ylim(0,NA)
  },
  res = 96)
  
  output$iris <- renderPlot({
    ggplot(iris, aes_string(x = input$x, y = input$y)) +
      geom_point(size = 1)
  },
  res = 96)
})

## Run shiny app
shinyApp(ui, server)
Shiny applications not supported in static R Markdown documents