Pedro Soares
Pedro Soares

Reputation: 35

Conditional formatting of cells for datatable in R

I want to change the color of a cell if two conditions are met. Let's take mtcars dataframe as an example, if vs=1 and cyl>=6 I want the cyl cell green and if vs=1 and cyl<6 I want the cyl cell yellow.

This should be the final result:

enter image description here

My issue is that I can't do and/or conditions with functions like formatStyle

Thanks!

Upvotes: 1

Views: 3592

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84709

An option using 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))
)

Another option:

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

Upvotes: 1

Related Questions