【问题标题】:Cell coloring in Shiny RendertableShiny Rendertable 中的单元格着色
【发布时间】:2017-02-03 05:06:32
【问题描述】:

我有一个非常简单的问题。我正在尝试有条件地为shinyrenderTable 的某些单元格着色。出于某种原因,下面的方法是将一个单元格向右着色,并将行中的单元格也推到一列上:

test <- data.frame(test1 = c(1:3), test2 = c(4:6))
test[test$test1 == 1, "test1"] <- '<td style="background-color:red">'

library(shiny)

ui <- shinyUI(fluidPage(
   tableOutput("tt")
   )
)

server <- shinyServer(function(input, output) {

   output$tt <- renderTable({
     test
   }, sanitize.text.function = function(x) x)
})

shinyApp(ui = ui, server = server)

这是一个错误吗?当我检查 HTML 输出时,我看到它留下了一个空白的&lt;td&gt; &lt;/td&gt; 单元格并创建了一个新的&lt;td style="background-color:red"&gt;。我也试过了:

test[test$test1 == 1, "test1"] <- '<td bgcolor="#FF0000">1</td>'

其他样式有效:

test[test$test1 == 1, "test1"] <- "<strong>1</strong>"

我试图避免更复杂的解决方案,例如:

R shiny color dataframe

这是否太简单而无法工作?非常感谢。

【问题讨论】:

  • 您只想使用 renderTable?或者可能是 HtmlTable 或 DT ?
  • @Batanichek 为简单起见,我想坚持使用 renderTable。如果做不到,我可以使用其他函数和包(看起来 DT 是用于表格的方式,所以我可能还是应该开始学习它)。

标签: html r shiny


【解决方案1】:

如果您只想使用 renerTable 进行操作,可以尝试将 div 添加到 td

示例

(但您可能需要一些 css 操作来获得相同的文本位置)

test <- data.frame(test1 = c(1:3), test2 = c(4:6))
test[test$test1 == 1, "test1"] <- '<div style="width: 100%; height: 100%; z-index: 0; background-color: green; position:absolute; top: 0; left: 0; padding:5px;">
<span>1</span></div>'

library(shiny)

ui <- shinyUI(fluidPage(
  tableOutput("tt"),
  tags$head(tags$style("#tt td{
                       position:relative;
                       };
                       
                       "))
  )
  )

server <- shinyServer(function(input, output) {
  
  output$tt <- renderTable({
    test
  }, sanitize.text.function = function(x) x)
})

shinyApp(ui = ui, server = server) 

在 DT 中你可以这样做:

test <- data.frame(test1 = c(1:3), test2 = c(4:6))

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  DT::dataTableOutput("tt")
)
)

server <- shinyServer(function(input, output) {
  
  output$tt <- DT::renderDataTable({
    datatable(test)%>%formatStyle("test1",backgroundColor=styleEqual(1, "red"))
  })
})

shinyApp(ui = ui, server = server)

正如您在 DT 版本中看到的,您不需要任何 css 样式等

【讨论】:

  • 太漂亮了。很惊讶这个方法之前没有发布过。
猜你喜欢
  • 1970-01-01
  • 2018-11-20
  • 2021-05-10
  • 1970-01-01
  • 2013-01-09
  • 2011-08-19
  • 2016-05-08
  • 1970-01-01
相关资源
最近更新 更多