Search code examples
rdataframeshinydropdowndatalist

R Shiny - create a table and populate it with the data frame data selected in drop down menu


I am continuing my struggles through R & R Shiny and have a question. I have a list of data frames. I want to use the names of the data frames from this list, to populate selectInput, and based on the selection of the data frame, I want to be able to view selected data frame, and see the statistics of its columns. So far I have found this code

shinyServer(function(input, output) {

    reactive_df <- reactive({
      if(input$x=="All")
        return df
      else
        return(select(df, starts_with(input$x)))
    }

    output$x <- renderDataTable(reactive_df())

}

But it does not do exactly what I want. Does anyone know how to create the table and the summaries?


Solution

  • You could have a look at mastering shiny:

    ui <- fluidPage(
      selectInput("dataset", label = "Dataset", choices = ls("package:datasets")),
      verbatimTextOutput("summary"),
      tableOutput("table")
    )
    
    server <- function(input, output, session) {
      output$summary <- renderPrint({
        dataset <- get(input$dataset, "package:datasets")
        summary(dataset)
      })
      
      output$table <- renderTable({
        dataset <- get(input$dataset, "package:datasets")
        dataset
      })
    }
    
    shinyApp(ui=ui,server=server)
    

    If you have your own list of dataset, you can use [[...]] instead of get:

    datasetlist <- list(iris = iris, mtcars = mtcars)
    data <- datasetlist[[input$datasetname]]
    

    for example if input$datasetname=='iris', you can check that this will assign iris to data for further processing:

    data <- datasetlist[["iris"]]
    data
    

    Another option is :

    data <- eval(parse(text=input$datasetname))