How to display in shiny app a matrix A with cell c

2019-08-04 06:09发布

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 !!

标签: r shiny dt
1条回答
ら.Afraid
2楼-- · 2019-08-04 06:44

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.

enter image description here

查看更多
登录 后发表回答