问题
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":
cbind
the "conditions-matrix" M and the "values-matrix" X,- Hide the columns belonging to the conditions-matrix using the
options
argument indatatable
. - Set the hidden columns as
valueColumns
and the non-hidden columns ascolumns
inDT::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