A Shiny App that Visualizes Miles per Gallon as predicted by Horsepower

Regis O'Connor
December 30, 2016

Project Overview

This Shiny App is similar to the app demonstrated in the Data Products Coursera Class, week 4. Although I created 2 other Shiny Apps from scratch each failed to operate in shinyio. Therefore, I retrenched and modified the class example with new content.

  • This was built in R version 3.3.2 on December 30, 2016.
  • It uses the mtcars data package.
  • It has 2 interactive features - choosing the mpg and which of 2 models to use for prediction.
  • The following 3 slides include the code for the ui.R and server.R files.
  • Thank you for your time in reviewing my work. I hope to see you again in the upcoming Data Science Capstone!

ui.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("Predict MPG from Horsepower"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("sliderHP",
                  "What is the Horsepower of the Car?",
                  52, 335, value = 100),
      checkboxInput("showModel1", "Show/Hide Model 1",
                    value=TRUE),
      checkboxInput("showModel2", "Show/Hide Model 2",
                    value=TRUE),
      submitButton("Submit")
    ),
    mainPanel(
      plotOutput("plot1"),
      h3("Predicted MPG from Model 1:"),
      textOutput("pred1"),
      h3("Predicted MPG from Model 2:"),
      textOutput("pred2")
    )
  )
))

server.R - part 1

library(shiny)
shinyServer(function(input,output){
  mtcars$hpsp <- ifelse(mtcars$hp-100>0, mtcars$hp-100,0)
  model1 <- lm(mpg~hp, data = mtcars)
  model2 <- lm(mpg~hp+hpsp, data=mtcars)
  model1pred <- reactive({
    hpInput <- input$sliderHP
    predict(model1, newdata=data.frame(hp = hpInput))
  })
  model2pred <- reactive({
    hpInput <- input$sliderHP
    predict(model2, newdata = data.frame(hp=hpInput,             hpsp=ifelse(hpInput-100>0,                      hpInput-100,0)))
  })

server.R - part 2

output$plot1 <- renderPlot({
    hpInput <- input$sliderHP
    plot(mtcars$hp, mtcars$mpg, xlab="Horsepower",
         ylab="Miles per Gallon", bty="n", pch=16,
         xlim=c(52,335), ylim=c(10,35))
    if(input$showModel1){
      abline(model1,col="green", lwd=2)
    }
    if(input$showModel2){
      model2lines <- predict(model2, new=data.frame(
        hp=52:335, hpsp = ifelse(52:335-100>0, 52:335-100, 0)
      ))
      lines(52:335, model2lines, col="blue", lwd=2)
    }
    legend(25,250,c("Model 1 Prediction", "Model 2 Predition"),
           pch=16, col=c("green", "blue"), bty="n", cex=1.2)
    points(hpInput, model1pred(), col="green", pch=16, cex=2)
    points(hpInput, model2pred(), col="blue",  pch=16, cex=2)       
  })

    output$pred1 <- renderText({
      model1pred()
    })
    output$pred2 <- renderText({
      model2pred()
    })
})