Batanichek Batanichek - 2 months ago 14
R Question

DT change color on diag

Is there way to change color of target cell in

DT
? or some cells by row and col index?

For example I have :

library(DT)
set.seed(123)
options(DT.options = list(pageLength = 5))
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))

datatable(df)%>% formatStyle(
'V6',
backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)


Thats look like :
enter image description here

I can change color for row or cell ( based on cells at current row)

But i cant find way to change color based on col and row index like :

enter image description here

Answer

Find one may be not best way -- generate rowCallback based on ncol of data.frame

Like

datatable(df,options = list(rowCallback=JS(paste("function(row, data,index) {",
                                                 paste(sapply(1:(ncol(df)),function(i) paste("
                                                   var ind_1=",i,";
                                                   $(this.api().cell(row,ind_1).node()).css({'background-color':index +1>ind_1 ? '#CCFFCC' : index+1 < ind_1 ? 'red' : 'yellow'});
                                                   "
                                                 )),collapse = "\n"),"}" )
                                                 )))

Result

enter image description here

Comments