在R闪亮中动态创建表时出错

问题描述 投票:1回答:1

我有一个数据帧,我希望在这种情况下根据年份过滤和创建表。我现在有4年了。所以我想创建4个新表并在闪亮的应用程序上单独显示它们。我确实得到循环的部分并传递过滤器变量但是如何创建4个新表并在UI中显示它们。我能够获得动态tabpanels但库(闪亮)

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)
r shiny
1个回答
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)
  })
© www.soinside.com 2019 - 2024. All rights reserved.