繁体   English   中英

如何调整数据表(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 function 。

但是现在formatStyle对此不起作用,并且没有更改宽度。 我想手动为每一列赋予不同的宽度,特别是使用占用大量空间的复选框( select )减小第一列的宽度。

在此处输入图像描述

你知道我该怎么做吗?

您可以将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)

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

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

问题是您可以将选项作为列表传递给columnDefs 该特定选项是说第五列(索引从 0 开始)具有 class dt-right (右对齐内容),其宽度是表格的 10%。 您可以在targets中传递具有多个元素的向量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM