How to show values in hidden columns for 'datatable' (R) in a correct format?

Viewed 182

There is an extension for "datatables" in R called "Responsive". It adds the "green plus" button on the left side of the row. By clicking on it we can get the view with "hidden" columns.

Here is an example. The "visible" column "mpg_percents_visible" has correct format (3%) when "hidden" column "mpg_percents_hidden" has incorrect formatting in extended view (0.0326644890340644).

library(DT)

# 1. Data set
df_mtcars <- mtcars %>% 
  mutate(
    mpg_percents_visible = mpg / sum(mpg),
    mpg_percents_hidden = mpg / sum(mpg)) %>% 
  select(mpg_percents_visible, everything())

# 2. Datatable
datatable(df_mtcars, extensions = c('Responsive')) %>% 
  formatPercentage(c('mpg_percents_visible', 'mpg_percents_hidden'))

How show hidden column "mpg_percents_hidden" in a correct format (3%)?

Thanks!

1 Answers

The formatPercentage function overwrites the cells data with the help of the rowCallback option of Datatables, and this has no effect on the hidden columns. The thing to do is to make the change in the render function of the columnDefs option (so you have to write the formatting in JavaScript).

library(dplyr)
library(DT)

df_mtcars <- mtcars %>% 
  mutate(
    mpg_percents_visible = mpg / sum(mpg),
    mpg_percents_hidden = mpg / sum(mpg)) %>% 
  select(mpg_percents_visible, everything())

render <- c(
  'function(data, type, row, meta){',
  '  if(type === "display"){',
  '    return (100*parseFloat(data)).toFixed(0) + "%";',
  '  }else{',
  '    return data;',
  '  }',
  '}'
)

datatable(
  df_mtcars, 
  extensions = c('Buttons', 'Responsive'), 
  options = list(
    responsive = TRUE,
    columnDefs = list(
      list(targets = 13, render = JS(render))
    )
  )) %>% 
  formatPercentage('mpg_percents_visible')

enter image description here

I learnt that here. Note that:

The only potential gotcha with this would be if something changes - columns.render is only called once and then cached, whereas that calculation in rowCallback is called on each draw. If the data is static, then what I suggested would be fine.

Related