根据另一个矢量设置Shiny tableOutput中列的背景颜色

Set background color of columns in Shiny tableOutput based on another vector

本文关键字:背景 颜色 tableOutput Shiny 另一个 设置      更新时间:2023-09-26

我有一个数据矩阵,我将在一个闪亮的应用程序中显示tableOutput格式。我有一个由颜色名组成的向量,它与代码无关。我需要设置[I]栏的背景颜色为[I]。

例如,如果我有以下内容:

helpme <- data.frame(matrix(rnorm(200),nrow=20))
helpme.colors <- c(rep("white",6),
               "chocolate4",
               "darkblue",
               rep("black",2))

然后,我要做的是这样的功能(R'ish伪代码):

for(i in 1:dim(helpme)[2]){
  BackgroundColor(helpme[,i]) <- helpme.colors[i]
} 

我想答案是一个相当简单的javascript循环,但我还没能找到它(我对javascript的经验很少)。

你可以使用一些r包

1) DT

library(DT)
ddd=datatable(helpme)
for (i in  1:ncol(helpme)){
  ddd=ddd%>%formatStyle(i,backgroundColor=helpme.colors[i])
}
ddd

2) htmlTable

htmlTable::htmlTable(helpme,css.cell=sapply(1:ncol(helpme),function(i) paste0("background-color:",helpme.colors[i],"")))

PS "chocolate4"有问题

<标题> 更新

DT的闪亮例子

library(shiny)
library(DT)
helpme.colors <- c(rep("white",1),
                   "chocolate",
                   "lightblue",
                   rep("black",10))
ui=shinyUI(
  fluidPage(textInput("txt_",label = "txt",""),
    DT::dataTableOutput("tt")
  )
)

server=shinyServer(function(input, output) {
  dd=reactive({
    data.frame(x=1:10,y=2:11,input$txt_)
  })
  output$tt=DT::renderDataTable({
    ddd=datatable(dd())
    for (i in  1:ncol(dd())){
      ddd=ddd%>%formatStyle(i,backgroundColor=helpme.colors[i])
    }
    ddd
  }
  )
})
shinyApp(ui,server)