这个问题与this有关,但是我要限定的值不是单元格的值,而是一个可用的外部列,但未在DT中显示。
我的例子很简单:
DT::datatable(
iris[,1:4],
editable = TRUE,
filter = c("bottom"),
rownames = FALSE,
extensions = 'Buttons',
options = list(
pageLength=21, scrollY='400px',
dom = 'Brt'
))%>% formatStyle('Sepal.Length', fontWeight = styleInterval(5, c('normal', 'bold')))
如何根据Sepal.Length
的值对列iris$Species
进行颜色编码或应用格式
Species
为setosa
,则为蓝色,并且Species
为versicolor
,则为红色,并且Species
为virginica
,则为绿色答案 0 :(得分:2)
这应该可以完成
library(DT)
DT::datatable(
iris,
editable = TRUE,
filter = c("bottom"),
rownames = FALSE,
extensions = 'Buttons',
options = list(
columnDefs = list(list(targets = 4, visible = F)),
pageLength= 150, scrollY='400px',
dom = 'Brt'
)) %>% formatStyle(
'Sepal.Length', 'Species',
backgroundColor = styleEqual(c("setosa", "versicolor","virginica"), c('steelblue', 'red', "green"))
)
答案 1 :(得分:1)
这是一个解决方案:
columnDefs
隐藏所需的列; initComplete
中使用一些Javascript设置颜色。jscode <- "function(settings) {
var table = settings.oInstance.api();
var nrows = table.rows().count();
for(var i=0; i<nrows; i++){
var cell0 = table.cell(i,0);
var cell4 = table.cell(i,4);
var species = cell4.data();
var bgcolor;
if(species == 'setosa'){
bgcolor = 'blue';
}else if(species == 'versicolor'){
bgcolor = 'red';
}else{
bgcolor = 'green'
}
cell0.node().style.backgroundColor = bgcolor;
}
}"
DT::datatable(
iris,
editable = TRUE,
filter = c("bottom"),
rownames = FALSE,
extensions = 'Buttons',
options = list(
pageLength=21, scrollY='400px',
dom = 'Brtp',
columnDefs = list(list(visible=FALSE, targets=4)),
initComplete = JS(jscode)
))%>% formatStyle('Sepal.Length',
fontWeight = styleInterval(5, c('normal', 'bold')))