当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

I have a matrix of data, which I will display in a Shiny app in tableOutput format. And I have a vector of colornames determined exogenous to the code. I need to set the background of column[i] to color[i].

For instance, if I have the following:

helpme <- data.frame(matrix(rnorm(200),nrow=20))

helpme.colors <- c(rep("white",6),

"chocolate4",

"darkblue",

rep("black",2))

Then, what I am looking to do is something that'd function like this (R'ish pseudocode):

for(i in 1:dim(helpme)[2]){

BackgroundColor(helpme[,i]) <- helpme.colors[i]

}

I imagine the answer is a fairly straighforward javascript loop but I haven't been able to find it yet (I have minimal experience in javascript).

网友答案:

You can use some r package

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 there is problem with "chocolate4"

Update

Shiny example of 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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: