March 14, 2020

Week 4 Assignment

  • One of the desirable properties of a car is it's power level and when car shopping this often is a focus of the buyer. However, when looking to estimate the operating cost in the long term of owning a car, fuel costs can be a factor. This app provides a quick calculation for the user to help determine a desirable power level and an acceptable fuel economy.

  • This app utilizes the data from the MT Cars data set and enables the user to input a particular horsepower level of a car using the slider bar.

  • After making a choice, a plot is generated to show the relationship between Horsepower (HP) and Fuel Economy (MPG) along with the estimated value of the fuel economy for a particular power level of the user's choice.

UI Code

The following is the UI code required for the app:

library(shiny)
shinyUI(fluidPage(
  titlePanel("Predict MPG from HP"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("sliderHP","What is the HP of the Car?",10,400,value=200)
    ),
  mainPanel(
    
    plotOutput("mpgPlot"),
    h3("Predicted mpg from Model:"),
    textOutput("Prediction")
  )
)
))

Server Code

The following is the server code used in the app.

library(shiny)
shinyServer(function(input,output){
  model_mpg=lm(mpg ~ hp,data=mtcars)
  model_mpg_predict=reactive({
    HPInput=input$sliderHP
    predict(model_mpg,newdata=data.frame(hp=HPInput))
  })
  output$Prediction=renderText({
    model_mpg_predict()
  })
  output$mpgPlot=renderPlot({
    HPInput=input$sliderHP
    plot(mtcars$hp,mtcars$mpg,xlab="Horsepower",ylab="MPG",xlim=c(10,600),ylim=c(0,40),
         points(HPInput,model_mpg_predict(),col="blue",pch=16,cex=2))
  })
})

Using the App

  • Enjoy the app and its use in relating power output and fuel economy.