wylie
wylie

Reputation: 193

incorporating JS callback function into RShiny DT::renderdatatable options

I am building a Shiny app and leveraging the DTedit library to allow users to edit data tables inline in the UI. This is working well, but I want to add some additional formatting to the tables (making some columns appear as percents, making other columns appear as dollar amounts). The problem with this is that the output of a DTedit function is a rendered output object (it expects to be passed directly to the UI - I can't do any paste0 or sapply operations on it).

The only upside is that I can pass dataframe options arguments to the DTEdit function before the output gets rendered - this includes the ability to pass JS Callbacks. Something like this:

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

The example above is showing changing the background color of the header to black, but as I mentioned, I'm interested in formatting several columns as percents / dollar amounts.

So this is all well and good, but the only problem is I know nothing about JS! I'm looking for guidance on building the correct JS callback to format my data table - thanks in advance!

Upvotes: 0

Views: 448

Answers (1)

David Fong
David Fong

Reputation: 546

I'm afraid I don't know Javascript either, but I know enough R to have modified DTedit to allow formatting with DT's format*() functions.

A modified version of DTedit is available on my Github repository, and is referenced as a pull request on jbryer/DTedit.

A vignette is available, look under 'formatting columns', and the example code is reproduced below, using the mtcars dataset.

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)

The formatting done is, by and large, not actually appropriate to the mtcars dataset, but used just as an example. Picture of formatted mtcars table

Upvotes: 1

Related Questions