gpt4 book ai didi

r - 以shiny方式输出N张表,其中N取决于数据

转载 作者:行者123 更新时间:2023-12-01 22:49:58 24 4
gpt4 key购买 nike

我有一个shiny应用程序,我想在其中打印多个表格。问题是,我不知道我会提前有多少张 table ——这取决于数据。例如。如果变量“X”有 5 个级别,我想输出 5 个表 - 一个对应于变量的每个级别。

为了生成表格,我在 server.R 中调用 renderTable() 内的函数,并将其分配给 output 插槽,如下所示:

output$tablePyramid <- renderTable ({
tableGeneratingFunction(argument1, argument2, ...)
})

如果我在 renderTable() 中放置多个“tableGenerateFunction”,它只会返回最后生成的表。所以看起来每个 output 槽只有一张表。我想我可以在 server.R 文件中处理这个问题,根据需要动态分配尽可能多的 output 插槽。

但我还必须列出 ui.R 文件中的所有输出。两个表的示例摘录:

mainPanel(
tabsetPanel(
... some code

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

我是否必须在其自己的 tableOutput 函数中列出每个表,或者是否有更优雅的方法来继续,因为我事先不知道有多少 tableOutput我需要?

最佳答案

我从迪特对我的问题(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"))
})

执行uiOutput()其中Ui.R :

    ... code        
uiOutput("tables")
... code

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

关于r - 以shiny方式输出N张表,其中N取决于数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com