MK
July 2, 2016
Data from mtcars show that vehicle weight is the number 1 predictor of fuel efficiency.
Compared to all other potential predictors, the correlation between 'wt' and 'mpg' is the strongest at -0.86:
wt cyl disp hp carb qsec
-0.8676594 -0.8521620 -0.8475514 -0.7761684 -0.5509251 0.4186840
gear am vs drat mpg
0.4802848 0.5998324 0.6640389 0.6811719 1.0000000
Assuming a linear relationship between the dependent variable 'mpg' and the independent variable 'wt,' a simple regression function would allow plugging in weight in tons to calculate a predicted mpg for a given vehicle:
mpgPredict <- function(weight) {
mtcarsWeight<-mtcars$wt
mtcarsMPG<-mtcars$mpg
lm1<-lm(mtcarsMPG ~ mtcarsWeight)
coeffs = coefficients(lm1); coeffs
estimateMPG = coeffs[1] + coeffs[2]*weight
names(estimateMPG) <- "Miles Per Gallon"
round(estimateMPG, digits = 1)
}
mpgPredict <- function(weight) {
mtcarsWeight<-mtcars$wt
mtcarsMPG<-mtcars$mpg
lm1<-lm(mtcarsMPG ~ mtcarsWeight)
coeffs = coefficients(lm1); coeffs
estimateMPG = coeffs[1] + coeffs[2]*weight
names(estimateMPG) <- "Miles Per Gallon"
round(estimateMPG, digits = 1)
}
The file server.r contains the function used to predict mpg based on weight and rendering instructions for the information on the web page:
mpgPredict <- function(weight) {
mtcarsWeight<-mtcars$wt
mtcarsMPG<-mtcars$mpg
lm1<-lm(mtcarsMPG ~ mtcarsWeight)
coeffs = coefficients(lm1); coeffs
estimateMPG = coeffs[1] + coeffs[2]*weight
names(estimateMPG) <- "Miles Per Gallon"
round(estimateMPG, digits = 1)
}
shinyServer(
function(input, output) {
output$inputValue <- renderPrint({input$weight})
output$prediction <- renderPrint({mpgPredict(input$weight)})
}
)