如何调整数据表(DT)中选定列的宽度

How to adjust the width of selected columns in datatable (DT)

我正在尝试调整 shiny 中数据表 DT 的宽度,这适用于下面的简单示例 -

library(magrittr)
library(shiny)
library(DT)

ui <- fluidPage(
  DT::dataTableOutput('dt')
)

server <- function(input, output) {
  output$dt <- DT::renderDataTable({
    dt1 <- head(mtcars)
    
    DT::datatable(dt1, rownames = FALSE) %>% 
      DT::formatStyle(columns = c(3,6), width='200px')
  })
}

shinyApp(ui, server)

然而,我的实际数据表有点复杂,并且有一些 javascript 功能。

ui <- fluidPage(
  DT::dataTableOutput('dt', width = '700px')
)

server <- function(input, output) {
  shinyInput = function(FUN, len, id, ...) {
    inputs = character(len)
    for (i in seq_len(len)) {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    }
    inputs
  }
  
  output$dt<- DT::renderDataTable({
    dt1 <- head(mtcars)
    df <- cbind(select = shinyInput(shiny::checkboxInput, nrow(dt1), 'check'),dt1)
    
    DT::datatable(df, selection = 'none', escape = FALSE,options = list(
      preDrawCallback = htmlwidgets::JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = htmlwidgets::JS('function() { Shiny.bindAll(this.api().table().node()); } '))) %>%
      DT::formatStyle(columns = c(3,6), width='200px')
  })
}

shinyApp(ui, server)

我从 复制了 shinyInput 函数。

但现在 formatStyle 对此不起作用,宽度也没有改变。我想手动为每一列提供不同的宽度,特别是使用复选框 (select) 减少第一列的宽度,这会占用很多 space.

你知道我该怎么做吗?

以下内容摘自我的一个应用程序,希望对您有所帮助

DT::datatable(
  data = data,
  options = list(
    columnDefs = list(
      list(width = "10%", class = "dt-right", targets = 4)
    )
  )
)

关键是您可以在 columnDefs 中将选项作为列表传递。该特定选项表示第五列(索引从 0 开始)具有 class dt-right(右对齐内容)并且其宽度为 table 的 10%。您可以在 targets.

中传递一个包含多个元素的向量

您可以将 width 值传递给 shiny::checkboxInput :

df <- cbind(select = shinyInput(shiny::checkboxInput, nrow(dt1), 'check', width = '10px'),dt1)

完整的应用程序代码 -

ui <- fluidPage(
  DT::dataTableOutput('dt', width = '700px')
)

server <- function(input, output) {
  shinyInput = function(FUN, len, id, ...) {
    inputs = character(len)
    for (i in seq_len(len)) {
      inputs[i] = as.character(FUN(paste0(id, i), label = NULL, ...))
    }
    inputs
  }
  
  output$dt<- DT::renderDataTable({
    dt1 <- head(mtcars)
    df <- cbind(select = shinyInput(shiny::checkboxInput, nrow(dt1), 'check', width = '10px'),dt1)
    
    DT::datatable(df, selection = 'none', escape = FALSE,options = list(
      preDrawCallback = htmlwidgets::JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = htmlwidgets::JS('function() { Shiny.bindAll(this.api().table().node()); } '))) %>%
      DT::formatStyle(columns = c(3,6), width='200px')
  })
}

shinyApp(ui, server)