在循环中渲染数据表

发布于 2025-02-13 12:07:21 字数 785 浏览 0 评论 0原文

它们都应该表现一样

library(shiny)

getData = function(name){
    if(name=='foo'){
        return(data.frame(foo=c('foo')))
    }else{
        return(data.frame(bar=c('bar')))
    }
}

ui <- fluidPage(
    DT::dataTableOutput(outputId = "foo"),
    DT::dataTableOutput(outputId = "bar")
)

server <- function(input, output) {
    for(item in c('foo','bar')){
        output[[item]] = DT::renderDT(getData(item))
    }
}

shinyApp(ui = ui, server = server)

我想在闪亮的应用中展示多个表,并且由于 相同的数据集(上面的示例中的“ bar”),特别是循环中的最后一个数据集。 似乎结构输出[[item]] = ...的行为不像我认为应该这样做,但我无法弄清楚发生了什么。

多谢!

I want to display multiple tables in a shiny-app, and as they should all behave the same, I thought I could render them in a for-loop:

library(shiny)

getData = function(name){
    if(name=='foo'){
        return(data.frame(foo=c('foo')))
    }else{
        return(data.frame(bar=c('bar')))
    }
}

ui <- fluidPage(
    DT::dataTableOutput(outputId = "foo"),
    DT::dataTableOutput(outputId = "bar")
)

server <- function(input, output) {
    for(item in c('foo','bar')){
        output[[item]] = DT::renderDT(getData(item))
    }
}

shinyApp(ui = ui, server = server)

Although the loop iterates correctly through the different 'datasets', all the tables finally show the same dataset ('bar' in the example above), notably the last one called in the loop.
It seems that the structure output[[item]] = ... doens't behave the way I think it should, but I can not figure out what is going on.

Thanks a lot!

resulting app from the code above

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

破晓 2025-02-20 12:07:21

您可以使用local如下所示

server <- function(input, output) {
  for(item in c('foo','bar')){
    local({
      item <- item
      output[[item]] = DT::renderDT(getData(item))
    })
    
  }
}

You can use local as shown below

server <- function(input, output) {
  for(item in c('foo','bar')){
    local({
      item <- item
      output[[item]] = DT::renderDT(getData(item))
    })
    
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文