我正在构建一个显示DataTable的Shiny仪表板。

我的目标是使数据表的列宽自动调整以适合单元格值在1行而不是多行中。但是,我得到了以下结果:

javascript - 如何在R Shiny数据表中设置列宽?-LMLPHP

似乎Name已根据我的需要进行了调整,但Notes没有。然后,我点击了这些链接:
https://rstudio.github.io/DT/options.html

Setting column width in R Shiny DataTable does not work in case of lots of column

R Shiny set DataTable column width

基本上,在线建议的解决方案是在呈现数据表时将autoWidth = TRUE参数与columnDefs一起使用。

这对我也不起作用,下面是结果:

javascript - 如何在R Shiny数据表中设置列宽?-LMLPHP

与初始结果相比,表格的宽度似乎变窄了

下面是我的最终代码:

header <- dashboardHeader(
  title = "Test"
)

sidebar <- dashboardSidebar(
)

body <- dashboardBody(
            box(title = "Test", width = 7, status = "warning", DT::dataTableOutput("df"))
)

# UI
ui <- dashboardPage(header, sidebar, body)

# Server
server <- function(input, output, session) {

  output$df = DT::renderDataTable(df, options = list(
    autoWidth = TRUE,
    columnDefs = list(list(width = '10px', targets = c(1,3)))))
    }

# Shiny dashboard
shiny::shinyApp(ui, server)


我不确定为什么可以使用单元格值的长度来调整“名称”列的宽度,但是不能对Notes的宽度进行调整。我也尝试在其他项目中使用数据表,列的宽度只能用列名的长度进行调整。

在我的情况下,另一种选择是将列宽设置为仅一定数量的字符,并通过将鼠标悬停在单元格上来显示单元格值的完整上下文。建议的解决方案在这里:R Shiny Dashboard DataTable Column Width。但是,这仅适用于DT,但是当我将其集成到Shiny中时却无法解决。

提前致谢。

最佳答案

如果不想多行,可以将CSS属性white-space: nowrap添加到所需列的单元格中。

由于您处于Shiny状态,因此可以很容易地做到这一点,只需定义CSS类并将其分配给className选项中的columnDefs到列即可:

library(DT)
library(shiny)

dat <- data.frame(
  V1 = c("A", "B"),
  V2 = c(
    "A cool guy living in US and Canada",
    "A cool guy living in California"
  ),
  V3 = c(
    "A cool guy living in US and Canada",
    "A cool guy living in California"
  ),
  V4 = c(
    "A cool guy living in US and Canada",
    "A cool guy living in California"
  ),
  V5 = c(
    "A cool guy living in US and Canada",
    "A cool guy living in California"
  ),
  stringsAsFactors = FALSE
)

css <- "
.nowrap {
  white-space: nowrap;
}"

ui <- fluidPage(
  tags$head(
    tags$style(HTML(css))
  ),
  DTOutput("table")
)

server <- function(input, output){

  output[["table"]] <- renderDT({
    datatable(dat,
              options = list(
                columnDefs = list(
                  list(className = "nowrap", targets = "_all")
                )
              ))
  })
}

shinyApp(ui, server)


javascript - 如何在R Shiny数据表中设置列宽?-LMLPHP

关于javascript - 如何在R Shiny数据表中设置列宽?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55208855/

10-12 12:39
查看更多