How to display in shiny app a matrix, specifying the color with conditionals?

安稳与你 提交于 2020-01-14 15:57:10

问题


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})
  }
)


来源:https://stackoverflow.com/questions/46365197/how-to-display-in-shiny-app-a-matrix-specifying-the-color-with-conditionals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!