6

Formattable have some easy options to format table, for example:

library(shiny)
library(DT)
library(formattable)

  df <- formattable(iris, lapply(1:4, function(col){

    area(col = col) ~ color_tile("red", "green")

This can later be coverted to a DT datatable

df <- as.datatable(df)

For me it works perfefect to view in the Viewer in RStudion. However, I would like to deploy it as a Shiny app somehow. Complete code:

library(DT)
library(shiny)

ui <- fluidPage(
  DT::dataTableOutput("table1"))


server <- function(input, output){

  df <- formattable(iris, lapply(1:4, function(col){

    area(col = col) ~ color_tile("red", "green")

  }))

  df <- as.datatable(df)

  output$table1 <- DT::renderDataTable(DT::datatable(df))

}

shinyApp(ui, server)

This does not work, is there any work around? I like the conditional formatting from formattable, but would also like to use some options that DT offers as for example filtering, searching, colvis etc.

To just deploy it as a formattable there is a thread:

How to use R package "formattable" in shiny dashboard?

Prasanna Nandakumar
  • 4,295
  • 34
  • 63
MLEN
  • 2,162
  • 2
  • 20
  • 36

1 Answers1

8

Yes it seems to be possible, as also mentioned here. Here is some sample code on how to achieve that:

library(shiny)
library(data.table)
library(formattable)

ui <- fluidPage(
  selectInput("input1","Species: ", choices = c("setosa", "versicolor", "virginica")),
  DT::dataTableOutput("table1"))

# make a data.table of the iris dataset. 
df <- iris

server <- function(input, output){

  output$table1 <- DT::renderDataTable( {

    my_df <- df[df$Species==input$input1,]

    return(as.datatable(formattable(my_df, lapply(1:4, function(col){area(col = col) ~ color_tile("red", "green")}))))
  }
  )

}

shinyApp(ui, server)
Florian
  • 24,425
  • 4
  • 49
  • 80
  • Did you manage to run this on your computer? I copy pasted and getting bracket errors, but everything seems ok... – MLEN Jul 25 '17 at 12:11
  • Sorry, that was sloppy. I made a modification to my code while already copied to Stack Overflow, but I missed a bracket. Please see my updated answer. – Florian Jul 25 '17 at 12:15
  • How can I add addtional argument to DT now? For example escape rownames. – MLEN Jul 25 '17 at 12:22
  • You can pass all arguments in the as.datatable call, the function is described in [the documentation of formattable](https://cran.r-project.org/web/packages/formattable/formattable.pdf). Hope this helps! – Florian Jul 25 '17 at 12:25