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:
Your list needs names, as discussed in PorkChop's answer. If this were the only required change, then PorkChop's answer would suffice.
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 theenvir=
argument ofls
andget
require an object, not thecharacter
name of an object. (One could go "inception" and usels(get("ls_df"))
and similarly forget
, 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 }) }