【问题标题】:incorporating JS callback function into RShiny DT::renderdatatable options将 JS 回调函数合并到 RShiny DT::renderdatatable 选项中
【发布时间】:2020-09-07 14:11:51
【问题描述】:

我正在构建一个 Shiny 应用程序并利用 DTedit 库来允许用户在 UI 中内联编辑数据表。这很好用,但我想为表格添加一些额外的格式(使某些列显示为百分比,使其他列显示为美元金额)。这样做的问题是 DTedit 函数的输出是一个渲染的输出对象(它希望直接传递给 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'});",
    "}")
))

上面的示例显示将标题的背景颜色更改为黑色,但正如我所提到的,我对将几列格式化为百分比/美元金额感兴趣。

所以这一切都很好,但唯一的问题是我对 JS 一无所知!我正在寻找有关构建正确的 JS 回调以格式化我的数据表的指导 - 在此先感谢!

【问题讨论】:

  • 您查看过 DT 包中的 format* 函数吗?

标签: javascript shiny dt


【解决方案1】:

恐怕我也不懂 Javascript,但我对 R 的了解足以修改 DTedit 以允许使用 DTformat*() 函数进行格式化。

DTeditis available on my Github repository 的修改版本,引用为a pull request on jbryer/DTedit

一个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

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2020-09-18
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2021-05-01
    • 2018-10-06
    相关资源
    最近更新 更多