如何在闪亮的应用程序中显示矩阵,并指定条件颜色? [英] How to display in shiny app a matrix, specifying the color with conditionals?

查看:58
本文介绍了如何在闪亮的应用程序中显示矩阵,并指定条件颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有正值和负值的矩阵M。我正在尝试使用DT包在闪亮的应用程序中显示为表格。我想用不同的颜色显示矩阵。红色的正数和负数(例如)。

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

到目前为止,我只能以一对一的方式添加颜色。但是我想以这种方式添加颜色:如果matrix_values> 0 color1,如果matrix_values< 0 color2。

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

推荐答案

您可以使用 DT :: styleInterval 代替 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,RStudio中的这些行将在查看器窗格中显示格式化的矩阵。如果您不使用RStudio,也可以在闪亮的应用程序中显示表格。

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

这篇关于如何在闪亮的应用程序中显示矩阵,并指定条件颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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