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

标签 javascript html r shiny rstudio

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

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

enter image description here

似乎名称已按我想要的方式调整,但注释没有。然后,我点击了这些链接: 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

这对我来说也不起作用,结果如下:

enter image description here

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

下面是我的最终代码:

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)

我不知道为什么Name列的宽度可以随着单元格值的长度调整,但Notes却不能。我也在其他项目中尝试过使用数据表,列的宽度只能通过列名的长度来调整。

在我的例子中,另一个选项是将列宽设置为仅一定数量的字符,并通过将鼠标悬停在单元格上来显示单元格值的完整上下文。此处建议解决方案:R Shiny Dashboard DataTable Column Width 。不过,这只是针对DT,但是当我将其集成到Shiny中时,它并没有起作用。

提前致谢。

最佳答案

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

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

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)

enter image description here

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

相关文章:

javascript - 如何使用 GJS 判断窗口是否最小化?

javascript - document.getElementById ('' ).src == ??? (等于失败)

javascript - 尝试将 VAR 设置为 DIV 的名称

r - mutate_impl(.data, 点) : Evaluation error: non-numeric argument to binary operator 中的错误

javascript - 从 <p> 中获取所有 <em> 并将它们像标签一样输出

javascript - 切换到卫星 View 时隐藏标签再次出现

jquery - 有什么方法可以支持 bootstrap 工具提示中的 HTML 标签代码吗?

html - Nginx:如何让重写规则忽略文件或文件夹

R - 添加具有几乎相同名称的列并使用正确的列名称保存

r - 单列对象的动物园列名