How to display in shiny app a matrix A with cell color depending of the cells of another matrix B?

六月ゝ 毕业季﹏ 提交于 2019-12-24 09:57:51

问题


I have a matrix M with positive values and negative values. I have another matrix X (dim(X) = dim(M)). I am trying to display X as a table in shiny app, using the DT package. I would like to display the matrix X with different colors conditioned by the values of M. It means: color1 in cells of X where M > 0 (X[M>0]) , color2 in cells of X where M<0 (X[M<0]) and color3 in cells of X where M == 0 (X[M == 0]).

The next code shows where I got stuck: X <- matrix(c(1:9), 3) M <- matrix(c(-3:2), 3) # The matrix is more complex and it's created in a reactive environment. Here is only an example

         X_colors <- reactive({

             DT::datatable(X()) %>% 
               formatStyle(
               columns = c(1:3),
               valueColumns(¿How do reference to M matrix?),
               backgroundColor = styleInterval(c(-1,0), c("lightgreen", 
               "lightred", "lightblue")
             ))
           })
          output$X_table_2 <- DT::renderDataTable(X_colors())

thanks !!


回答1:


What you ask for is possible but not very straightforward. My approach includes using hidden columns. My "recipe":

  1. cbind the "conditions-matrix" M and the "values-matrix" X,
  2. Hide the columns belonging to the conditions-matrix using the options argument in datatable.
  3. Set the hidden columns as valueColumns and the non-hidden columns as columns in DT::formatStyle

library(DT)
library(dplyr)   # for %>%

print(M <- matrix(c(-3:2), 3))
#      [,1] [,2]
# [1,]   -3    0
# [2,]   -2    1
# [3,]   -1    2
print(X <- matrix(letters[1:6], 3))
#      [,1] [,2]
# [1,] "a"  "d" 
# [2,] "b"  "e" 
# [3,] "c"  "f"

cbind(M, X) %>% datatable(
  options = list(columnDefs = list(list(visible = FALSE, targets = 0:1)))
) %>%
  formatStyle(
    columns = 3:4,
    valueColumns = 1:2,
    backgroundColor = styleInterval(c(-.01, 0), c("red", "white", "green"))
  )

Notice that I used targets = 0:1 to hide columns 1:2 since this parameter follows javascript syntax where indexing begins with 0 rather than 1.



来源:https://stackoverflow.com/questions/46367017/how-to-display-in-shiny-app-a-matrix-a-with-cell-color-depending-of-the-cells-of

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