Home > OS >  Why does this Shiny App not display dataframe using RStudio?
Why does this Shiny App not display dataframe using RStudio?

Time:06-13

I have a list of data frames, ls_df, comprising two dataframes from the datasets package.

I am trying to load these two dataframes into a Shiny app using the code below. However, it does not work, with the error message no item called "ls_df" on the search list being returned. Does anyone know how to fix?

ls_df <- list(datasets::airmiles,
datasets::AirPassengers)


ui <- fluidPage(
  selectInput("ls_df", label = "Dataset", choices = ls("ls_df")),
  verbatimTextOutput("summary"),
  tableOutput("table")
)

server <- function(input, output, session) {
  output$summary <- renderPrint({
    dataset <- get(input$ls_df, "ls_df")
    summary(dataset)
  })
  
  output$table <- renderTable({
    dataset <- get(input$ls_df, "ls_df")
    dataset
  })
}
shinyApp(ui, server)

CodePudding user response:

The list needs the names:

library(shiny)
ls_df <- list(airmiles=datasets::airmiles,AirPassengers=datasets::AirPassengers)

ui <- fluidPage(
  selectInput("ls_df", label = "Dataset", choices = names(ls_df)),
  verbatimTextOutput("summary"),
  tableOutput("table")
)

server <- function(input, output, session) {
  output$summary <- renderPrint({
    dataset <- ls_df[[input$ls_df]]
    summary(dataset)
  })
  
  output$table <- renderTable({
    dataset <- ls_df[[input$ls_df]]
    dataset
  })
}
shinyApp(ui, server)

CodePudding user response:

Two things wrong:

  1. Your list needs names, as discussed in PorkChop's answer. If this were the only required change, then PorkChop's answer would suffice.

  2. get(input$ls_df, "ls_df") is an error. This should be rather clear, though, since it prevents the shiny interface from starting. This error is because the envir= argument of ls and get require an object, not the character name of an object. (One could go "inception" and use ls(get("ls_df")) and similarly for get, but that hardly seems necessary or useful.)

    ls_df <- list(airmiles=datasets::airmiles,                       # <-- named list
                  AirPassengers=datasets::AirPassengers)
    
    
    ui <- fluidPage(
      selectInput("ls_df", label = "Dataset", choices = ls(ls_df)),  # <-- no quotes
      verbatimTextOutput("summary"),
      tableOutput("table")
    )
    
    server <- function(input, output, session) {
      output$summary <- renderPrint({
        dataset <- get(input$ls_df, ls_df)                           # <-- no quotes
        summary(dataset)
      })
    
      output$table <- renderTable({
        dataset <- get(input$ls_df, ls_df)                           # <-- no quotes
        dataset
      })
    }
    
  • Related