R中数据表的单元格条件格式

Conditional formatting of cells for datatable in R

如果满足两个条件,我想更改单元格的颜色。让我们以 mtcars 数据帧为例,如果 vs=1cyl>=6 我想要 cyl 单元格绿色,如果 vs=1cyl<6 我想要cyl 单元格黄色。

这应该是最终结果:

我的问题是我不能用像 formatStyle

这样的函数做 and/or 条件

谢谢!

使用JavaScript的选项:

library(DT)

js <-  c(
  "function(settings) {",
  "  var table = settings.oInstance.api();",
  "  var nrows = table.rows().count();",
  "  for(var i=0; i<nrows; i++){",
  "    var vs = table.cell(i,8);",
  "    var cyl = table.cell(i,2);",
  "    if(vs.data() == 1){",
  "      cyl.node().style.backgroundColor = cyl.data() >= 6 ? 'green' : 'yellow';",
  "    }",
  "  }",
  "}")

datatable(mtcars, 
          options = list(initComplete = JS(js))
)

另一个选项:

dat <- mtcars
dat$colors <- with(dat, ifelse(vs==1, ifelse(cyl>=6, "green", "yellow"), "white"))
datatable(dat, 
          options = list(
            columnDefs = list(
              list(visible = FALSE, targets = 12)
            )
          )
) %>% formatStyle("cyl", valueColumns = "colors", backgroundColor = JS("value"))