格式化数据框中的列,包括带有 DT 的小部件

Formatting columns in a dataframe including widgets with DT

我正在尝试格式化由 DT 呈现的数据框(为特定列添加颜色,更改字体,...),并且我正在考虑使用 DT 中可用的格式函数(即 formatStyle, formatCurrency).

但是,这些函数只能在数据表上使用,我无法将我的数据框转换为数据表,因为它破坏了我在特定列中插入的不同小部件。

library(shiny)

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

df <- iris

df$hist <- shinyInput(actionButton, nrow(df), "hist_", label = "Hist", onclick = 'Shiny.onInputChange(\"select_button\",  this.id)' )
df$num <- shinyInput(numericInput, nrow(df), "num_", label = NULL, value=NULL)

ui <- dashboardBody(box(fluidPage(DT::dataTableOutput('DTdf'))))

server <- function(input, output){
  dfDT <- reactive({df})
  output$DTdf <- DT::renderDT(
    dfDT(),  
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))
}

shinyApp(ui=ui, server=server)

我尝试像这样替换 renderDT 函数的第一个参数,但小部件停止工作。

output$DTdf <- DT::renderDT(
    datatable(dfDT()),  
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')))

我发现格式化列的一个解决方案是直接使用 HTML 代码更改它们的内容,例如,如果我想将物种的喜好更改为粗体:

df$Species <- paste0("<div><b>", df$Species, "</b></div>")

但这会导致我的程序出现很多问题,我正在寻找一种解决方案来仅更改 DToutput 的视觉方面,而不更改数据框中的数据。

试试这个

server <- function(input, output){
  dfDT <- reactive({df})

  output$DTdf <- DT::renderDT({
    datatable(dfDT(),
    escape=F,
    options = list(
      preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
      drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } '))) })
}