gpt4 book ai didi

r - 如何为 DT 表的给定行间隔赋予颜色?

转载 作者:行者123 更新时间:2023-12-02 05:27:07 25 4
gpt4 key购买 nike

我正在使用 DT 库来可视化表格,但假设我想为某些行指定颜色,例如从第 1 行到第 4 行为红色:

enter image description here

如果可能的话,更改文本的颜色也非常好。经过几个小时的搜索,我从 DT 库中找到了这个函数:

datatable(df, rownames = FALSE) %>%
formatStyle(columns = "inputval",
background = styleInterval(c(0.7, 0.8, 0.9)-1e-6, c("white", "lightblue", "magenta", "white")))

但是我需要为所有列提供颜色,而不仅仅是代码中的 inputval 之类的选定列,我可以为 columns 值提供类似 names( df) 这样它就可以为所有列提供颜色? styleInterval 选择表中的值而不是行的间隔,我该怎么做才能选择行并给它们指定颜色?

最佳答案

像这样的东西应该可以完成工作。请注意,我故意将行着色为 2:4,而不是 1:4,以获得更多功能:

library(shiny)
library(DT)

ui <- basicPage(
mainPanel(DT::dataTableOutput('mytable'))
)

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

output$mytable = DT::renderDataTable(
DT::datatable(mtcars, options = list(
pageLength = 25,
rowCallback = JS('function(row, data, index, rowId) {',
'console.log(rowId)','if(rowId >= 1 && rowId < 4) {',
'row.style.backgroundColor = "pink";','}','}')
)
)
)




}
runApp(list(ui = ui, server = server))

enter image description here

编辑:动态为行着色:这里我只是使用sub来替换范围来为行着色

library(shiny)
library(DT)

fnc <- JS('function(row, data, index, rowId) {',
'console.log(rowId)','if(rowId >= ONE && rowId < TWO) {',
'row.style.backgroundColor = "pink";','}','}')

ui <- basicPage(
sliderInput("colorrows", "Which to color:",min = 0, max = 10, value = c(1,3)),
mainPanel(DT::dataTableOutput('mytable'))
)

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

Coloring <- eventReactive(input$colorrows,{
fnc <- sub("ONE",input$colorrows[1],fnc)
fnc <- sub("TWO",input$colorrows[2],fnc)
fnc
})

output$mytable = DT::renderDataTable(
DT::datatable(mtcars, options = list(pageLength = 25,rowCallback = Coloring())
)
)
}
runApp(list(ui = ui, server = server))

enter image description here

关于r - 如何为 DT 表的给定行间隔赋予颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45542144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com