将 JS 回调函数合并到 RShiny DT::renderdatatable 选项中

incorporating JS callback function into RShiny DT::renderdatatable options

我正在构建一个 Shiny 应用程序并利用 DTedit 库允许用户在 UI 中内联编辑数据 tables。这运行良好,但我想向 table 添加一些额外的格式(使某些列显示为百分比,使其他列显示为美元金额)。这个问题是 DTedit 函数的输出是渲染输出 object(它预计会直接传递给 UI - 我不能对其执行任何 paste0 或 sapply 操作)。

唯一的好处是我可以在呈现输出之前将数据帧选项参数传递给 DTEdit 函数——这包括传递 JS 回调的能力。像这样:

datatable(head(iris, 20), options = list(
  initComplete = JS(
    "function(settings, json) {",
    "$(this.api().table().header()).css({'background-color': '#000', 'color': '#fff'});",
    "}")
))

上面的示例显示了将 header 的背景颜色更改为黑色,但正如我所提到的,我有兴趣将多个列的格式设置为百分比/美元金额。

所以这一切都很好,但唯一的问题是我对JS一窍不通!我正在寻找有关构建正确的 JS 回调以格式化我的数据的指导 table - 提前致谢!

恐怕我也不知道 Javascript,但我知道 R 足以修改 DTedit 以允许使用 DTformat*() 函数。

DTeditis available on my Github repository, and is referenced as a pull request on jbryer/DTedit的修改版本。

A vignette is available, look under 'formatting columns',下面使用 mtcars 数据集复制示例代码。

library(DTedit)
library(magrittr) # provides the pipe '%>%' operator

server <- function(input, output, session) {
  dtedit(
    input, output,
    name = 'mtcarstable',
    thedata = mtcars,
    datatable.rownames = TRUE, # needed for the format*() functions to work
    datatable.call = function(...) {
      datatable(...) %>%
        formatSignif('qsec', 2) %>%
        formatCurrency('mpg') %>%
        formatStyle(
          'cyl',
          color = 'red', backgroundColor = 'orange', fontWeight = 'bold'
        )
      # note, none of this is proper formatting for the mtcars data!
      # but serves to demonstrate the formatting
    }
  )
}

ui <- fluidPage(
  h3('mtcars'),
  uiOutput('mtcarstable')
)

shinyApp(ui = ui, server = server)

大体上,完成的格式化实际上并不适合 mtcars 数据集,只是用作示例。 Picture of formatted mtcars table