-->

How to display in shiny app a matrix, specifying t

2019-07-09 01:16发布

问题:

I have a matrix M with positive values and negative values. I am trying to display as a table in shiny app, using the DT package. I would like to display the matrix with different colors. Positive numbers in red and negative numbers (for example).

So far, I only can add colours in a one-to-one way . But I want to add colours in this way: if matrix_values > 0 "color1", if matrix_values < 0 "color2".

 M <- matrix(c(-3:2), 3) # The matrix is more complex and it's created in a 
 reactive environment. Here is only an example

 M_out <- reactive({

 DT::datatable(M()) %>% 
   formatStyle(
     columns = c(1:7),
     backgroundColor = styleEqual(c( 0, 1), c("green", "red")
   ))
 })
 output$X_table_2 <- DT::renderDataTable(M_1X2())

Thanks !!

回答1:

You can use DT::styleInterval instead of DT::styleEqual

library(DT)      # for datatable, formatStyle, styleInterval
library(dplyr)   # for %>%

myDT <- matrix(c(-3:2), 3) %>% datatable %>% 
  formatStyle(
    columns = 1:2,
    backgroundColor = styleInterval( 
      cuts = c(-.01, 0), 
      values = c("red", "white", "green")
    )
  )

myDT

Runnig these lines in RStudio will display the formatted matrix in the viewer pane. If you are not using RStudio, you can also show the table in a shiny app.

library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('table'))
  server = function(input, output, session){
    output$table = DT::renderDataTable({myDT})
  }
)


标签: r shiny dt