Regis O'Connor
December 30, 2016
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.
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")
)
)
))
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)))
})
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()
})
})