Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force scientific notation with renderDT

Tags:

I would like the behaviour of numeric values in DT tables to be the same than in the print output when using :

options(scipen = -1)
options(digits = 3)
cars/1000000

enter image description here

But whatever are the options, it seems that DT do not care about it: enter image description here

I know that print is not the same as rendering a table, but there should be a way to do it. I can play with signif or round to limit digits but I am losing information with very low values and this affects high values differently.

  • I want to keep values as numeric so that the column can be sorted correctly.
  • Values should be kept classical if only 3 digits, and scientific if more.

Here is the minimal example.

library(shiny)
library(DT)
library(dplyr)

options(scipen = -1)
options(digits = 3)

# Define UI for application that draws a histogram
ui <- fluidPage(
   # Application title
   titlePanel("Old Faithful Geyser Data"),
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
      ),
      # Show a plot of the generated distribution
      mainPanel(
         DTOutput("dt"),
         DTOutput("dt2")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
   output$dt <- renderDT({cars/1000000})
   output$dt2 <- renderDT({
     mutate_all(cars/1000000, funs(signif(., digits = 1)))
     })
}
# Run the application 
shinyApp(ui = ui, server = server)

Any clues ?

like image 316
Sébastien Rochette Avatar asked Apr 03 '18 15:04

Sébastien Rochette


2 Answers

The DT package also has a formatSignif() function that can help with this, e.g.:

output$tbl <- renderDataTable({
    DT::datatable(dat) %>%
        formatSignif(columns = c('speed', 'dist'), digits = 3)
})
like image 132
Keith Hughitt Avatar answered Sep 23 '22 11:09

Keith Hughitt


You could try using a rowCallback to change the notation to scientific using the toExponential javascript function.

Here's an example:

library(shiny)
library(DT)
library(dplyr)

# Define UI for application that draws a histogram
ui <- fluidPage(
  # Application title
  titlePanel("Old Faithful Geyser Data"),
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
    ),
    # Show a plot of the generated distribution
    mainPanel(
      DTOutput("dt")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  output$dt <- renderDT({
    datatable(cars/10,options = list(
      rowCallback = JS(
        "function(row, data) {",
        "for (i = 1; i < data.length; i++) {",
        "if (data[i]>1000 | data[i]<1){",
        "$('td:eq('+i+')', row).html(data[i].toExponential(1));",
        "}",
        "}",
        "}")
    )
    )
  })
}
# Run the application 
shinyApp(ui = ui, server = server)
like image 25
NicE Avatar answered Sep 22 '22 11:09

NicE