闪亮地动态选择列表和renderTable中的元素

时间:2018-12-05 10:07:40

标签: r list shiny shinydashboard

我有一个l的列表data.frames,并且我想用selectInput动态选择元素。

一旦用户选择了一个元素,我希望能够在幕后使用它,例如在renderTable中使用它并输出该data.frame的表。

此外,我希望能够在列表中选择该元素,并应用lm

我面临的问题在这里:l[[ElemInput()]]如何转换带有反应性元素的经典R代码?

完整的shinydashboard

library(shiny)
library(shinydashboard)


ui <- dashboardPage(
  dashboardHeader(
    title = "My Dashboard"
  ),
  dashboardSidebar(
    sidebarMenu(
      menuItem("aaa", tabName = "aaa", icon = icon("dashboard"))
    )
  ),
  dashboardBody(
    tabItems(
      # First tab content
      tabItem(tabName = "aaa",
              h2("Dashboard aaa"),
              fluidRow(
                box(
                    selectInput("input_name", "Select input:", choices = names(l))
                ),
                box(
                  dataTableOutput('table')
                )
              )
      )
    )
  )
)

server <- function(input, output) { 
  # create a fake list 
  set.seed(123)
  l <- list(element1 = data.frame(aaa=1:5, bbb=sample(5)),
            element2 = data.frame(ccc=6:10, ddd=sample(5)))

  # reactive read element
  ElemInput <- reactive({
    input$input_name
  })

  # render table
    output$table <- renderTable({
      l[[ElemInput()]] #  this part doesn't work
    })

}

shinyApp(ui, server)

可能相关的问题,但我无法为我的案件找到解决方案:

dynamically list 'choices' for selectInput from a user selected column

Store selectInput in a string/character object

1 个答案:

答案 0 :(得分:1)

您应在renderTable中将tableOutputui一起使用。因此,将dataTableOutput('table')更改为tableOutput('table')

如果您使用dataTableOutput,则可以使用renderDataTable

我也更喜欢使用观察者而不是反应函数。有点容易阅读。

server <- function(input, output) { 
  observeEvent(input$input_name,{
    # observe element change and render table
    output$table <- renderTable({
      data.frame(l[[input$input_name]])
    })
  })
}