如何从闪亮列表中的单个列表元素的renderDataTable或renderTable

时间:2019-09-23 14:16:09

标签: r shiny

说我有以下几点-注意myList

library(shiny)

myList <- list(
  first_element = tibble(a = 1, b = 2),
  second_element = tibble(a = 4:5, e = 7:8),
  third_element = tibble(a = c("one", "two", "three"), x = c("another", "another one", "another two"))
)

ui <- fluidPage(
  titlePanel("A Title"),
  verbatimTextOutput("pretty_output")
)

server <- function(input, output, session) {
  output$pretty_output <- renderPrint({
    myList
  })
}

shinyApp(ui, server)

结果是:

Shiny App

我想以编程方式将myList表示为单独的renderTablerenderDataTable元素。以下内容说明了一种蛮力方法,但我正在寻求通过使用for循环,lapplypurrr::map()和/或其他东西来更灵活,更D.R.Y.的东西。

注意:myList的长度应假定为未知。

library(shiny)
library(DT)

myList <- list(
  first_element = tibble(a = 1, b = 2),
  second_element = tibble(a = 4:5, e = 7:8),
  third_element = tibble(a = c("one", "two", "three"), x = c("another", "another one", "another two"))
)

ui <- fluidPage(
  titlePanel("A Title"),
  dataTableOutput("dt_01"),
  dataTableOutput("dt_02"),
  dataTableOutput("dt_03")
)

server <- function(input, output, session) {
  output$dt_01 <- renderDataTable({
     datatable(myList[[1]], caption = names(myList[1]))
  })

  output$dt_02 <- renderDataTable({
    datatable(myList[[2]], caption = names(myList[2]))
  })

  output$dt_03 <- renderDataTable({
    datatable(myList[[3]], caption = names(myList[3]))
  })

}

shinyApp(ui, server)

2 个答案:

答案 0 :(得分:1)

请检查以下base.Push方法:

Integer

答案 1 :(得分:0)

因此,我认为大多数方法都将涉及renderUI,这就是我所追求的(感觉很优雅),但是我将对此一无所知,以查看其他人是否可以加入。 this post

library(shiny)

myList <- list(
  first_element = tibble(a = 1, b = 2),
  second_element = tibble(a = 4:5, e = 7:8),
  third_element = tibble(a = c("one", "two", "three"), x = c("another", "another one", "another two"))
)

ui <- fluidPage(
  titlePanel("A Title"),
  uiOutput("tables")
)

server <- function(input, output, session) {

  # Create the outputs dynamically
  output$tables <- renderUI({

    tableList <- imap(myList, ~ {
      tagList(
        h4(.y), # Note we can sprinkle in other UI elements
        tableOutput(outputId = paste0("table_", .y))
      )
    })

    tagList(tableList)
  })

  # Now render each output
  iwalk(myList, ~{
    output_name <- paste0("table_", .y)
    output[[output_name]] <- renderTable(.x)
  })

}

shinyApp(ui, server)

Shiny App