在R Shiny中动态创建表时出错

时间:2018-09-19 20:47:43

标签: r shiny

在这种情况下,我有一个要根据年份过滤和创建表的数据框。我已经有4年了,所以我想创建4个新表并将其分别在闪亮的应用程序上显示。我确实获得了循环的一部分并传递了过滤器变量,但是如何创建4个新表并在UI中显示它们。我可以获取动态标签,但库(发光)

library(shinyWidgets)
library(shinydashboard)
library(DT)

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tab",
              menuItem("1", tabName = "1")
  )
)
body <-   ## Body content
  dashboardBody(box(
    uiOutput('mytabs')
    ))

ui <-   dashboardPage(dashboardHeader(title = "Scorecard"),
                      sidebar,
                      body)

# Define the server code
server <- function(input, output,session) {
  df <- data.frame(structure(list(`Mazda` = c(21000,20000,21500,24000), `Honda` = c(21500,20500,22000,24500)
                                  ,  Sales = c(2017,2015,2016,2014)
                                  )
                             , class = "data.frame", row.names = c(NA, -4L)))
  toAdd <- as.vector(df$Sales)

  for(i in length(toAdd)){
    print(length(toAdd))
  output[[paste0("datatable_",i)]] <- DT::renderDataTable({
   df %>% filter(Sales == toAdd[i])
  })
#}
 # for(i in 1:length(toAdd)){

  output$mytabs <- renderUI({
    nTabs = length(toAdd)
    # create tabPanel with datatable in it
    myTabs = lapply(seq_len(nTabs), function(i) {
      tabPanel(paste0("dataset_",toAdd[i]),
               DT::dataTableOutput(paste0("datatable_",i))
      )
    })

    do.call(tabsetPanel, myTabs)

  })
}
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:2)

您必须使用local,并且不要在循环中放入renderUI

  for(i in 1:length(toAdd)){
    local({
      ii <- i
      output[[paste0("datatable_",ii)]] <- DT::renderDataTable({
        df %>% filter(Sales == toAdd[ii])
      })
    })
  }

  output$mytabs <- renderUI({
    nTabs = length(toAdd)
    # create tabPanel with datatable in it
    myTabs = lapply(seq_len(nTabs), function(i) {
      tabPanel(paste0("dataset_",toAdd[i]),
               DT::dataTableOutput(paste0("datatable_",i))
      )
    })
    do.call(tabsetPanel, myTabs)
  })