App Summary - Gas Milage predictor

This app predicts the average gas use per mile based on a linear regression model considering the total weight, number of cylinders and transmission type of a car.

library(shiny)
library(ggplot2)

Data

  • R standard data set "mtcars"
  • contains the specifications of 32 different cars
  • Source: Henderson and Velleman (1981), Building multiple regression models interactively. Biometrics, 37, 391–411
data(mtcars)

Model

The linear model is based on the amount of cylinders, the total weight and the transmission type.

# Example data from app input
input <- data.frame(slider_cyl=4, numeric_wt=2.5,checkbox_am=TRUE)

#prediction <- reactive({
prediction <-  function(){  
    m<- lm(mpg ~ cyl + wt + as.logical(am) , data=mtcars) 
    prediction_parameters<-data.frame(cyl=input$slider_cyl, 
                        wt=input$numeric_wt,am=input$checkbox_am)
    y<- predict(m,prediction_parameters)    
    #print(y)
    return(y)   
  }

prediction<-mean(prediction())
prediction
## [1] 25.74

Plot

The code for creating the plot is shown below.

plotData<- mtcars[which(mtcars$am==input$checkbox_am),]

    plotData$line_name<-"Original data"
    predicted_point <- data.frame(mpg = mean(prediction), cyl = input$slider_cyl,
      disp = 1,  hp = 1, drat = 1, wt = input$numeric_wt, qsec = 1,
      vs = 1, am = 1, gear = input$checkbox_am, carb = 1, line_name = 'Prediction'
    )
    plotData<-rbind(plotData,predicted_point)
    plotData$cyl<-as.factor(plotData$cyl)
    p<-ggplot(data=plotData, aes(x=wt, y=mpg, color=cyl, shape=line_name)) + 
      ggtitle("Predicted milage based on total weight, amount of cylinders \n
              and transmission type") + 
      xlab("Total Weight (in tons)") + ylab("Miles per Gallon") +
      geom_point(size=5, alpha=0.5) +
      scale_color_discrete(name="Amount of cylinders") +
      scale_shape_discrete(name="Data points")

Example Plot

This is an example plot of the app.

p

plot of chunk unnamed-chunk-5