【发布时间】:2021-11-15 05:20:22
【问题描述】:
我有一些代码可以创建一个带有单选按钮的 DT 表。最重要的是,我需要为每一行添加特定的颜色。我一直在尝试使用 formatStyle 为每一行添加不同的颜色,但我没有得到正确的语法。
这是工作代码:
library(shiny)
library(DT)
c1 = "This is comment 1"
c2 = "This is comment 2"
c3 = "This is comment 3"
c4 = "This is comment 4"
c5 = "This is comment 5"
comments1 = list(c1,c2,c3,c4,c5)
m1 = matrix(
as.character(1:5), nrow = 5, ncol = 1, byrow = FALSE,
dimnames = list(comments1, LETTERS[1])
)
for (i in seq_len(ncol(m1))) {
m1[, i] = sprintf(
'<input type="radio" name="%s" value="%s"/>',
'AValue', m1[,i]
)
}
callback1 <- c(
"var LETTERS = ['AValue'];",
"for(var i=0; i < LETTERS.length; ++i){",
" var L = LETTERS[i];",
" $('input[name=' + L + ']').on('click', function(){",
" var name = $(this).attr('name');",
" var value = $('input[name=' + name + ']:checked').val();",
" Shiny.setInputValue(name, value);",
" });",
"}"
)
ui <- fluidPage(
title = 'Radio buttons in a table',
DT::dataTableOutput('foo1'),
verbatimTextOutput('sel1'),
)
server <- function(input, output, session) {
output$foo1 = DT::renderDataTable(
m1, escape = FALSE, selection = 'none', server = FALSE,
options = list(dom = 't', paging = FALSE, ordering = FALSE),
callback = JS(callback1),
)
output$sel1 = renderPrint({
input[["AValue"]]
})
}
shinyApp(ui, server)
以下是我尝试过的一些调用的不同变体。
#formatStyle needs to be called on DT:datatable()
#Test adding formatStyle
output$foo1 <- DT::renderDataTable({
dat <- datatable(m1, escape = FALSE, selection = 'none',
options = list(dom = 't', paging = FALSE, ordering = FALSE))
callback = JS(callback1) %>% formatStyle(0, target='row', backgroundColor = styleEqual(3,'red'))
})
或
#Test adding formatStyle
output$foo1 <- DT::renderDataTable({
DT::datatable(m1,escape = FALSE, selection = 'none',
options = list(dom = 't', paging = FALSE, ordering = FALSE, callback = JS(callback1))
%>% formatStyle(0, target='row', backgroundColor = styleEqual(3,'red')))
})
任何帮助将不胜感激。 谢谢!
【问题讨论】: