Assignment 6
Code
R
Plots
Assignment
The Shiny app has been created using the mtcars data set. The code for the app is given below. The app has been hosted at:
ui<- (fluidPage(
titlePanel("mtcars dataset"),
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 35,
value = 12),
checkboxInput("showmeanstd", 'Show/hide the mean value', value = TRUE),
sliderInput("sliderMPG",
"MPG of a car?",
min = 10,
max = 35,
value = 20),
checkboxInput("showmodel", 'Show/hide the predicted model', value = TRUE)
),
mainPanel(
tabsetPanel(
tabPanel("Plot",
fluidRow(
column(8, plotOutput("histPlot")),
column(8, h3("Predicted hoursepower from the model:"), textOutput("pred")),
column(8, plotOutput("lmplot"))
))
))
)
))
server<- function(input, output) {
output$histPlot <- renderPlot({
x <- mtcars$mpg
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'green', border = 'black', xlab = "MPG")
if (input$showmeanstd){
abline(v = mean(x), col = "red", lwd = 2)
abline(v = c(mean(x) - sd(x), mean(x) + sd(x)), col = "orange", lwd = 3, lty = 2)
}
})
model_lm <- lm(hp~mpg, data = mtcars)
model_lm_pred <- reactive({
mpgInput <- input$sliderMPG
predict(model_lm, newdata = data.frame(mpg = mpgInput))
})
output$lmplot <- renderPlot({
mpgInput <- input$sliderMPG
plot(mtcars$mpg, mtcars$hp, xlab = "MPG", ylab = "Hoursepower")
if (input$showmodel){
abline(model_lm, col = "red", lwd = 2)}
points(mpgInput, model_lm_pred(), col = "blue", pch = 16, cex = 2)
})
output$pred <- renderText({
model_lm_pred()})
}
shinyServer(function(input, output) {
output$histPlot <- renderPlot({
x <- mtcars$mpg
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = 'green', border = 'black', xlab = "MPG")
if (input$showmeanstd){
abline(v = mean(x), col = "red", lwd = 2)
abline(v = c(mean(x) - sd(x), mean(x) + sd(x)), col = "orange", lwd = 3, lty = 2)
}
})
model_lm <- lm(hp~mpg, data = mtcars)
model_lm_pred <- reactive({
mpgInput <- input$sliderMPG
predict(model_lm, newdata = data.frame(mpg = mpgInput))
})
output$lmplot <- renderPlot({
mpgInput <- input$sliderMPG
plot(mtcars$mpg, mtcars$hp, xlab = "MPG", ylab = "Hoursepower")
if (input$showmodel){
abline(model_lm, col = "red", lwd = 2)}
points(mpgInput, model_lm_pred(), col = "blue", pch = 16, cex = 2)
})
output$pred <- renderText({
model_lm_pred()})
})
shinyApp(ui,server)