R shiny 从相同的输出函数中检索表并并排显示在 ui 中

R shiny retrieve tables from same output function & show in ui side by side

我在服务器输出变量中有一个繁琐的函数。 函数 returns 2 个数据帧的列表。 我想提取这些表格并将它们并排绘制。 但是我不想在服务器中为它们创建两个不同的输出,因为我不希望重函数 运行 两次。

为了提供可重现的代码: (我的 getListOfDataFrames 函数比这个例子重得多) 我希望 df1 和 df2 在 options

中与 scrollX = TRUE 并排显示
library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput("output1")
)

server <- function(input, output){

  getListOfDataFrames <- function(df){
  return(list(df[1:5,], df[6:10,]))   
  }

  output$output1 <- renderDataTable({

    myList <- getListOfDataFrames(mtcars)

    df1 <- as.data.frame(myList[1])
    df2 <- as.data.frame(myList[2])

  })

}

shinyApp(ui, server)

有很多关于如何创建动态内容的示例,如下例所示:

library(shiny)
library(DT)

ui <- fluidPage(
  uiOutput("dt")
)

server <- function(input, output){

  getListOfDataFrames <- function(df){
    return(list(df[1:5,], df[6:10,]))   
  }

  myList <- getListOfDataFrames(mtcars)

  output$dt <- renderUI({
    ntables <- seq(myList)

    # we want to create the width depending how many tables we have
    width <- paste0(99/max(ntables),"%;")

    lapply(ntables, function(i) {
      id <- paste0("dt", i)
      div(style=paste0("display:inline-block;width:",width),DT::dataTableOutput(id))
    })
  })

  observe({
    # Dynamically creating 2 tables with separate ids
    lapply(seq(myList), function(i){
      id <- paste0("dt", i)
      output[[id]] <- DT::renderDataTable(as.data.frame(myList[i]))
    })
  })

}

shinyApp(ui, server)