在Shiny的dataTableOutput中控制表格宽度

24

我无法控制在Shiny应用程序中使用dataTableOutput()函数添加的datatable的宽度。我尝试使用函数内的width参数,但输出结果没有任何变化,并且也没有错误提示-它没有告诉我忽略了width参数。

library(shiny)
library(shinythemes)

ui <- fluidPage(theme = shinytheme("Spacelab"),
            fluidRow(
              column(6,dataTableOutput(outputId = "table")),
              column(6,p(textOutput("para")))
  )
)

server <- function(input, output){

  df <- as.data.frame(matrix(0, ncol = 15, nrow = 20))

  output$table <- renderDataTable({df})

  output$para <- renderText({
    text <- rep(x = "Hello World",1000)
  })
}
shinyApp(ui = ui,server = server)

我在shiny::dataTableOutput中没有看到width参数,但似乎来自DT包的dataTableOutput有一个。你是否在加载shiny之后加载了DT包?你也可以使用 DT::dataTableOutput - aosmith
如果我使用 DT 而不是 shiny,数据表是否仍然具有响应性? - Collin
请尝试这个SO答案 - Rivka
2个回答

42

dataTableOutput没有width参数。您可以在fluidRow中使用column并提供一个介于1和12之间的整数作为width参数。

library(shinythemes)
ui <- fluidPage(theme = shinytheme("Spacelab"),
    fluidRow(
        column(
            dataTableOutput(outputId = "table"), width = 6)
    )
)

server <- function(input, output){
    df <- as.data.frame(matrix(0, ncol = 20, nrow = 5))
    output$table <- renderDataTable({df}, 
        options = list(scrollX = TRUE))
}
shinyApp(ui = ui,server = server)

您可以直接通过renderDataTable参数选项传递JavaScript库DataTable中的选项。例如,将scrollX设置为true允许表格滚动。


3
我尝试使用列来更新示例,但似乎 dataTableOutput 不愿合作。 - Collin
3
在您最初的示例中,您有许多列。shiny仍然呈现网页,因此如果列太宽而无法适应窗格的子集,则表将使用页面可用部分显示。 - CSJCampbell
在您更新的示例中,textOutput 显示在正确的一半,而 dataTableOutput 在 Firefox 浏览器中会导致文本崩溃。您希望看到什么行为? - CSJCampbell
我想在指定区域中查看dataTableOutput。我认为您可以左右滚动以查看所有列。我尝试将表格放置在absolutePanel中,但它没有给出我想要的行为。感谢@CSJCampbell的帮助。 - Collin
2
@Collin 我已经更新了示例,演示如何为表格添加滚动条...你需要将JavaScript参数作为列表传递给renderDataTable - CSJCampbell

11
如果你使用 "DT" R软件包和相应的 DT:: dataTableOutput DT:: renderDataTable ,则可以在这些调用中使用 "width" 选项,该选项似乎可以是百分比(例如 width="100%")或像素(width=300),这将让你获得你想要的控制。
参见:https://rstudio.github.io/DT/shiny.html
请注意,从该页面中可知:
重要提示:一定要在调用dataTableOutput和renderDataTable时使用“DT ::”前缀,以确保调用DT版本的这些函数,而不是已弃用的Shiny版本。如果您在library(shiny)之后确保使用library(DT),通常情况下,如果您不使用DT ::前缀,则DT版本应该会覆盖闪亮的版本(当存在疑问时,请使用此前缀,直到我们完全从闪亮中删除这些函数)。

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