Shiny Application to Predict Acceleration

Suresh Subramaniam
1-1-2018

Introduction

This application takes the Horsepower as the input in a slider and predicts the Time in Seconds which the car takes to cover Quarter of a Mile.

Steps to use

  • Move the slider above to set the HP of the car.
  • The predicted time will be shown in the main panel
  • Select/Deselect the checkbox to show the best fit regression line

The code for the UI portion

#The UI code
library(shiny)
shinyUI(fluidPage(
    titlePanel("Predict the Time for a Quarter Mile from the Horsepower"),
    sidebarLayout(
        sidebarPanel(
            sliderInput("sliderHP", "What is the HP of the car?", 50, 350, value = 100),
            checkboxInput("showModel", "Show/Hide Model", value = TRUE)
        ),
        mainPanel(
            plotOutput("plot"),
            h4("Predicted Time in Sec for a Quarter Mile:"),
            textOutput("prediction"),
            h4("This application takes the Horsepower as the input in a slider and predicts the Time in Seconds which the car takes to cover Quarter of a Mile."),
            h4("Steps:"),
            h4("Move the slider above to set the HP of the car"),
            h4("The predicted time will be shown in the panel above"),
            h4("Select/Deselect the checkbox to show the best fit regression line")

        )
    )
))

<!–html_preserve–>

Predict the Time for a Quarter Mile from the Horsepower

Predicted Time in Sec for a Quarter Mile:

This application takes the Horsepower as the input in a slider and predicts the Time in Seconds which the car takes to cover Quarter of a Mile.

Steps:

Move the slider above to set the HP of the car

The predicted time will be shown in the panel above

Select/Deselect the checkbox to show the best fit regression line

<!–/html_preserve–>

The code for the Server portion

#The Server code
library(shiny)

shinyServer(function(input, output) {
    model <- lm(qsec ~ hp, data = mtcars)
    modelpred <- reactive({
        hpInput <- input$sliderHP
        predict(model, newdata = data.frame(hp = hpInput))
    })

    output$plot <- renderPlot({
        hpInput <- input$sliderHP

        plot(mtcars$hp, mtcars$qsec, xlab = "Horse power",
             ylab = "Seconds for Quarter Mile", bty = "n", pch = 16,
             xlim = c(50, 350), ylim = c(14, 23))
        if(input$showModel){
            abline(model, col = "red", lwd = 2)
        }
        points(hpInput, modelpred(), col = "red", pch = 16, cex = 2)
    })

    output$prediction <- renderText({
        modelpred()
    })
})

The Sample Output

plot of chunk unnamed-chunk-3