Ben Ben - 3 months ago 30
R Question

How do I format columns of a datatable using renderDataTable() in the DT package?

I can format a column of a datatable object like so

library(DT)
datatable(data.frame(Amount=c(1.00, 2.20, 4.15))) %>% formatCurrency(columns='Amount')


enter image description here

But how can I do this using
renderDataTable()
?

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
DT::dataTableOutput('dtoMyTable')
))

server <- shinyServer(function(input, output){
output$dtoMyTable <- DT::renderDataTable({
data.frame(Amount=c(1.00, 2.20, 4.15))
})
})

shinyApp(ui = ui, server = server)

Answer

Read the help page on DT::renderDataTable:

renderDataTable(expr, ...

expr
an expression to create a table widget (normally via datatable()), or a data object to be passed to datatable() to create a table widget

So you just create the datatable object first, format as you wish, then call renderDataTable.

server <- shinyServer(function(input, output){
  dt <- datatable(data.frame(Amount=c(1.00, 2.20, 4.15))) %>% 
    formatCurrency(columns='Amount')
  output$dtoMyTable <- DT::renderDataTable({dt})
})
Comments