如何在闪亮的应用程序中显示具有不同单元格颜色的矩阵A(取决于另一个矩阵B的单元格)? [英] How to display in shiny app a matrix A with cell color depending of the cells of another matrix B?

查看:56
本文介绍了如何在闪亮的应用程序中显示具有不同单元格颜色的矩阵A(取决于另一个矩阵B的单元格)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵 M ,其中包含正值和负值。我还有另一个矩阵 X (dim(X)= dim(M))。我正在尝试使用DT包将 X 显示为闪亮的应用程序中的表格。我想用 M 的值显示具有不同颜色的矩阵 X 。这意味着:X> M> 0(X [M> 0])的单元格中的 color1,M <0(X [M <0])的X单元格中的color2和X = M = 0的X单元格中的color3 = 0(X [M == 0])

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]).

下一个代码显示了我被卡住的地方:
X<-matrix(c(1:9),3)
M< -matrix(c(-3:2),3)#矩阵更加复杂,它是在
反应性环境中创建的。这只是一个例子

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

谢谢!!

推荐答案

您所要求的是可能的,但不是很简单。我的方法包括使用隐藏列。我的食谱:

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


  1. cbind 条件矩阵 M 和值矩阵 X

  2. 使用选项隐藏属于条件矩阵的列数据表中的参数。

  3. 将隐藏的列设置为 valueColumns 和非隐藏列作为 DT :: formatStyle
  4. $ b $中的 b
  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"))
  )

注意,我使用 targets = 0:1 隐藏列 1:2 ,因为此参数遵循javascript语法,其中索引以 0 而不是 1 开头。

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.

这篇关于如何在闪亮的应用程序中显示具有不同单元格颜色的矩阵A(取决于另一个矩阵B的单元格)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆