在Shiny Rendertable中进行单元格着色

3

我有一个非常简单的问题。我正在尝试对 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)

这是一个bug吗?当我检查HTML输出时,发现它会留下一个空的<td> </td>单元格,并创建一个新的<td style="background-color:red">。我也尝试过:

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

这种样式也是有效的:

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

我试图避免更复杂的解决方案,例如:R Shiny 颜色数据框。这是否太简单了?非常感谢。

你想要只使用renderTable吗?还是HtmlTable或DT? - Batanichek
@Batanichek 为了简单起见,我想坚持使用renderTable。如果不行的话,我可以使用其他函数和包(看起来DT是处理表格的最佳选择,所以我应该开始学习它)。 - Tunn
1个回答

4

如果你想仅使用renerTable实现它,可以尝试将

添加到中。

例子

(但你可能需要一些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样式等。

太棒了。非常惊讶这个方法以前没有被发布过。 - Tunn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接