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

时间:2019-03-17 15:45:52

标签: javascript html r shiny rstudio

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

我的目标是使数据表的列宽自动调整以适合单元格值在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中时却无法解决。

谢谢。

2 个答案:

答案 0 :(得分:1)

如果不想多行,可以将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)

enter image description here

答案 1 :(得分:0)

问题在于列宽度的索引是从0开始的基数,而不是1。在OP代码中,目标将第2列和第4列的宽度(设置为相对较窄的10px),而不是第1列和第3列。

尝试以下方法,

  

columnDefs = list(list(width ='200px',目标= c(0,2)))))

这应该使第一和第三列为200px,而其他所有列均为自动宽度。

相关问题