在Shiny中输出N个表格,其中N取决于数据

3
我有一个闪亮的应用程序,我想在其中打印多个表格。问题是,我事先不知道会有多少个表格 - 这取决于数据。例如,如果变量“X”有5个级别,则我希望输出5个表格 - 每个变量级别一个表格。
为了生成表格,在server.R中的renderTable()内调用一个函数,并将其分配给output插槽,如下所示:
output$tablePyramid <- renderTable ({
          tableGeneratingFunction(argument1, argument2, ...)
})

如果我在renderTable()中放置了多个"tableGeneratingFunction",它只会返回最后生成的表格。所以似乎每个output插槽只能有一个表格。我想我可以在server.R文件中处理这个问题,根据需要动态地分配尽可能多的output插槽。
但我还必须在ui.R文件中列出所有的输出。以下是两个表格的示例摘录:
mainPanel(
tabsetPanel(
... some code

  tabPanel(title="Proportions",
           tableOutput("tablePyramid"),
           tableOutput("tablePyramid2")
           ),
  ... some more code

我需要为每个表单都写一个tableOutput函数吗?还是有更好的办法,因为我事先不知道我需要多少个tableOutput

4
https://dev59.com/YGIk5IYBdhLWcg3wN71j - Dieter Menne
@DieterMenne:谢谢你提供的链接,很有帮助。 - Crt Ahlin
请检查最近的答案:https://dev59.com/ylwZ5IYBdhLWcg3wPONM - Beasterfield
1个回答

4
我从Dieter在我的问题(R Shiny - add tabPanel to tabsetPanel dynamically (with the use of renderUI))中提供的评论开始。原理相同-使用Server.R中的所有表格生成HTML,然后使用uiOutput()Ui.R中显示它。不同之处在于,我找不到shiny包中类似于tabPanel()的函数,该函数在给定示例中生成HTML。
但是,我可以使用xtable()生成HTML,并为表格传递一些额外的参数,以便在渲染时看起来符合shiny框架的预期。
下面是一个生成任意数量表格的HTML的函数示例:
tabelize <- function(variables, arg2, ...) {

  tables <- list() # create a list to hold all tables

  for (variable in variables) { # go through all possible values of variables
    table <- function_that_returns_a_data_frame(variable, arg2, ...)
    tables[[as.character(variable)]] <- 
      # save table into slot in created list
      # print table as HTML with additional formatting options
      print(xtable(table, caption=paste("Variable:", variable)),
            type="html",
            html.table.attributes='class="data table table-bordered table-condensed"',
            caption.placement="top")
  }
  return(lapply(tables, paste)) # return HTML tables pasted together
}

Server.R中调用该函数(带有一些额外选项),并将其分配给output$插槽。
output$tables <- renderUI({
  out <- tabelize(variables, arg2, ...) 
  # additional options to make rendering possible
  return(div(HTML(out),class="shiny-html-output"))
 })

在`Ui.R`中使用`uiOutput()`来执行它:
    ... code        
    uiOutput("tables")
    ... code

如果有更好的方法,请评论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接