Home > Mobile >  DT: format* overwrites columndefs
DT: format* overwrites columndefs

Time:11-18

I want to specify a certain column via columnDefs and then format the same column by format*. In this case I add a hover text over column B (column 2) and would like to color and round it later. When adding formatStyle to the datatable I still see the hover text, but other format functions such as formatRound seem to overwrite the columnDefs.

Is there a way to format a column using both columnDefs and format* in R without too much JS?

Here a reproducible example:

library(dplyr)
library(DT)

data <- tibble(A = c("A", "AB"), B = c(-1, 1))

js <- c(
  "function(data, type, row, meta) {",
  "return type === 'display' ?",
  "'<span title=\"'   'A: '   row[1]   '\">'   data: data;",
  "}"
)

dt <- DT::datatable(
  data,
  options = list(
    columnDefs = list(
      list(
        targets = 1,
        visible = FALSE
      ),
      list(
        targets = 2,
        render = JS(js)
      )
    )
  )
)
# hover still works
dt %>%
  formatStyle(columns = "B", color = styleInterval(0, c("red", "green")))

# hover doesn't work anymore
dt %>%
  formatRound(columns = "B")
dt %>%
  formatSignif(columns = "B")

CodePudding user response:

Doing it in JS is not "too much". For example, to round to 2 decimal digits:

js <- c(
  "function(data, type, row, meta) {",
  "  return type === 'display' ?",
  "    '<span title=\"'   'A: '   row[1]   '\">'  ", 
  "      Math.round(100*data)/100 : data;",
  "}"
)

Replace 100 with 1000 to round up to 3 digits, etc.

  •  Tags:  
  • rdt
  • Related