Loading a non-base R dataset in a shiny application

Viewed 86

I have an app which is meant to render a table of one of two possible datasets: either mtcars, which comes with base R's datasets package, or BostonHousing which comes with the mlbench package. For some reason I can't get this to run properly. Can anyone suggest a fix?

library(shiny)
library(mlbench)

ui <- fluidPage(
  selectInput("select", "Select", 
              choices = c("mtcars", "BostonHousing"),
              selected = "mtcars"),
  tableOutput("table")
)

server <- function(input, output, session) {
  dat <- reactive(data(input$select))
  output$table <- renderTable({
    dat()
  })
}

shinyApp(ui, server)

Edit: for clarification, the data frame must be stored in dat. The renderTable component is there only to confirm that it loaded successfully.

2 Answers
library(shiny)
library(mlbench)
library(DT)



ui <- fluidPage(
  selectInput("select", "Select", 
              choices = c("mtcars","BostonHousing"),
              selected = "mtcars"),
     DT::dataTableOutput("table")

)

server <- function(input, output, session) {

        data(BostonHousing)
        output$table <- DT::renderDataTable({
  
            DT::datatable(get(input$select))   
    })

}


shinyApp(ui, server)

Here is my take on it:

library(shiny)
library(mlbench)

ui <- fluidPage(
  selectInput("select", "Select", 
              choices = c("mtcars", "BostonHousing"),
              selected = "mtcars"),
  tableOutput("table")
)

server <- function(input, output, session) {
  dat <- reactive({
    data(input$select)
    get(input$select)
  })
  output$table <- renderTable({
    dat()
  })
}

shinyApp(ui, server)

What I've noted:

  • you use renderDataTable for a tableOutput, this does not work, either use renderTable/tableOutput or use datatable (best with the DT package)
  • data("BostonHousing") directly loads the object BostonHousing into the environment, whereas data("mtcars") only loads a promise, therefore I've added the get(input$select) to make it work for mtcars
Related