Batanichek Batanichek - 1 year ago 68
R Question

DT change color on diag

Is there way to change color of target cell in

? or some cells by row and col index?

For example I have :

options(DT.options = list(pageLength = 5))
df =, 3), 10), sample(0:1, 10, TRUE)))

datatable(df)%>% formatStyle(
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 Source

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


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"),"}" )


enter image description here