在 Shiny 中两次使用相同的输出元素

MLE*_*LEN 4 r datatables shiny

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

用户界面

navbarPage(
  title = 'DataTable Options',
  tabPanel('Display length',     DT::dataTableOutput('ex1')),
  tabPanel('Length menu',        DT::dataTableOutput('ex2'))
)
Run Code Online (Sandbox Code Playgroud)

服务器

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
      )
    )
  )

}
Run Code Online (Sandbox Code Playgroud)

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

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

Flo*_*ian 6

您的 ui 代码很好,但是:

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

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

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()
  )

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 仅供参考:这也有效。输出$ex2 &lt;- 输出$ex3 &lt;- DT::renderDataTable(iris_table()) (3认同)