2022-09-21

Developing Data Products Final

This presentation goes through the final projects for the Developing Data Products course.

Project Description

This project creates a Shiny app to create a prediction model on the mtcars dataset.

Build the UI

The ui.R file will include two text input boxes for the weight and horsepower, and a select box for the number of cylinders, which will be stored as a factor.

sidebarLayout(
        sidebarPanel(
            h2("Vehicle details:"),
            numericInput("weight", "    Weight (1000 lbs):", 0),
            numericInput("hp", "Horsepower:", 0),
            selectInput("cyl", "Number of cylinders:", c(4, 6, 8)),
            actionButton("action", "Calculate"),
        ),

        # Show the predicted MPG output
        mainPanel(
            h3("Predicted MPG:"),
            h4(textOutput("pred"))
        )
    )

Setup the Data For Use

In the server.R file, we have to run some code that sets up the data, selects the proper columns, and creates the regression model. The only columns that we’re interested in is the weight (wt), horsepower (hp), and the number of cylinders (cyl). We use those columns to predict the MPG.

mtcars$cyl <- factor(mtcars$cyl)
cardata <- mtcars %>%
    select(mpg, wt, hp, cyl)
model <- lm(mpg ~ wt + hp + cyl, cardata)

shinyServer function call.

In the server.r file, we include a call to observeEvent(). That function call allows us to read the user data in the text input and dropdown boxes.

shinyServer(function(input, output) {
    observeEvent(input$action, {
        wt <- input$weight
        hp <- input$hp
        cyl <- input$cyl
    
        df <- data.frame(wt = wt, hp = hp, cyl = cyl)
        output$pred <- renderText(predict(model, newdata = df))
    })
})