在 Shiny 中两次使用相同的输出元素 [英] Using the same output element twice in Shiny

查看:21
本文介绍了在 Shiny 中两次使用相同的输出元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例取自 Shiny 画廊.我想在第一个选项卡上显示 ex1 和 ex2,在第二个选项卡上的 ex2 和 ex2 之间有一些中断.

Example taken from Shiny gallery. I would like to show ex1 and ex2 on the first tab, with some breaks between and ex2 on the second tab.

ui.R

navbarPage(
  title = 'DataTable Options',
  tabPanel('Display length',     DT::dataTableOutput('ex1')),
  tabPanel('Length menu',        DT::dataTableOutput('ex2'))
)

server.R

function(input, output) {

  # display 10 rows initially
  output$ex1 <- DT::renderDataTable(
    DT::datatable(iris, options = list(pageLength = 25))
  )

  # -1 means no pagination; the 2nd element contains menu labels
  output$ex2 <- DT::renderDataTable(
    DT::datatable(
      iris, options = list(
        lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
        pageLength = 15
      )
    )
  )

}

我认为下面的代码会起作用,但它不会.它确实在任何选项卡中显示任何内容.

I thought the following code would work, but it does not. It does show anything in any of the tabs.

navbarPage(
  title = 'DataTable Options',
  tabPanel('Display length',     DT::dataTableOutput('ex1'),
           HTML("<br><br><br>"),
           DT::dataTableOutput('ex2')),
  tabPanel('Length menu',        DT::dataTableOutput('ex2'))
)

推荐答案

你的 ui 代码很好,但是:

Your ui code is fine, but:

Shiny 不支持多个同名输出.这段代码将生成两个元素具有相同 ID 的 HTML,即无效的 HTML.

Shiny doesn't support multiple outputs with the same name. This code would generate HTML where two elements have the same ID, which is invalid HTML.

所以,我认为您唯一的解决方案是创建第三个表.最好的选择是在中间使用反应式,这样你就可以避免两次使用相同的代码.

So, I think your only solution would be to create a third table. The best option is to use a reactive in the middle, so you avoid having the same code used twice.

function(input, output) {

  # display 10 rows initially
  output$ex1 <- DT::renderDataTable(
    DT::datatable(iris, options = list(pageLength = 25))
  )

  # -1 means no pagination; the 2nd element contains menu labels

  iris_table <- reactive({
    DT::datatable(
      iris, options = list(
        lengthMenu = list(c(5, 15, -1), c('5', '15', 'All')),
        pageLength = 15
      )
    )
  })

  output$ex2 <- DT::renderDataTable(
    iris_table()
  )
  output$ex3 <- DT::renderDataTable(
    iris_table()
  )

}

希望这有帮助!

这篇关于在 Shiny 中两次使用相同的输出元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆