且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用列和行名称或索引为R中的数据表(DT包)中的单元格背景着色?

更新时间:2023-01-25 21:28:34

我不确定问题,但是如果您想更改其行索引和列索引给定的单元格的背景颜色(这是我的理解),则可以执行以下操作:

  changeCellColor<-函数(行,列){
c(
函数(行,数据,数字,索引){,
sprintf( (index ==%d){,row-1),
sprintf( $('td:eq('+%d +')',row),col),
.css({'background-color':'orange'});;,
},
}

}
datatable(dat ,
options = list(
dom = t,
rowCallback = JS(changeCellColor(1,2))



Here is an example. I created a data frame and use that to create a datatable for visualization. As you can see, my column name and the row from the first column indicate conditions from A and B. What I want to do is to change the background color of a specific cell in this datatable. It is easy to select the column to change, as explained in this link (https://rstudio.github.io/DT/010-style.html). However, it is not obvious to me how to specify the row I want to select.

To give you more context, I am developing a Shiny app, and I would like to design a datatable allow me to color a cell based on the condition from A and B. For example, if A is less than 1 and B is between 1 and 2, I would like to be able to select the second cell from the A is less than 1 column. To acheive this, I will need to know how to specify the row number or row name. For now, I only know how to specify the rows based on the contents in the rows, as this example shows.

library(tibble)
library(DT)

dat <- tribble(
  ~`A/B`,                ~`A is less than 1`, ~`A is between 1 and 2`,  ~`A is larger than 2`,
  "B is less than 1",                    10,                      30,                     30,
  "B is between 1 and 2",                 20,                      10,                     30,
  "B is larger than 2",                   20,                      20,                     10
)


datatable(dat, filter = "none", rownames = FALSE, selection = "none",
          options = list(dom = 't', ordering = FALSE)) %>% 
  formatStyle(
  'A is less than 1',
   backgroundColor = styleEqual(20, "orange")
)

I'm not sure to get the question, but if you want to change the background color of a cell given by its row index and its column index (that's what I understand), you can do:

changeCellColor <- function(row, col){
  c(
    "function(row, data, num, index){",
    sprintf("  if(index == %d){", row-1),
    sprintf("    $('td:eq(' + %d + ')', row)", col),
    "    .css({'background-color': 'orange'});",
    "  }",
    "}"  
  )
}
datatable(dat, 
          options = list(
            dom = "t",
            rowCallback = JS(changeCellColor(1, 2))
          )
)