Week 4 Presentation on R Shiny

June 26, 2018

Background

Crime is something that many governments wish to curtail. As such, it is important to understand the relationships between difference variables to see how they might co-occur.

Description on App

The Shiny app allows the user to select 2 variables. Behind the scenes, the server runs a linear regression model on the 2 variables. The plot will display the fitted line with the raw data.

Please see this link for the App: https://assignments.shinyapps.io/Week4/

Instructions on Usage

  1. Select Y variable
  2. Select X variable
  3. The relationship between the 2 variables is summarized in the equation on the top of the plot

The Data

The US Arrests dataset comes in built to R. It is captured at a state level and and contains the following variables:

  • Murder Rate
  • Assult Rate
  • Urban Population
  • Rape Rate

Exploratory Data Analysis

Beginning with exploratory analysis on the US Arrests dataset plot of chunk unnamed-chunk-1

The Code: UI

library(shiny)
shinyUI(fluidPage(
    titlePanel("US Arrests: understanding the relationships between variables"),
  sidebarLayout(
    sidebarPanel(
      h4("Select Variables"),
      selectInput('ycol', 'Y Variable', names(USArrests),
                  selected=names(USArrests)[[2]]),
      selectInput('xcol', 'X Variable', names(USArrests))),
    mainPanel(
       h3("Scatter Plot and Linear Model", align = "center"),
       plotOutput("distPlot")))
  ))

<!–html_preserve–>

US Arrests: understanding the relationships between variables

Select Variables

Scatter Plot and Linear Model

<!–/html_preserve–>

The Code: Server

shinyServer(function(input, output, session) {
  selectedData <- reactive({
    USArrests[, c(input$xcol, input$ycol)]
  })
  model <- reactive({
    dat <- selectedData()
    model <- lm(dat[,2]~dat[,1], data = dat)
    return(model)
  })
  output$distPlot <- renderPlot({
    plot(selectedData(), xlab = "X Var", ylab = "Y Var")
    abline(model(), col = "red")
    mtext(paste('y =', round(coef(model())[[2]],1), '* x', '+', round(coef(model())[[1]],1)))
  })
})

Thank you!