glin / reactable

Interactive data tables for R
https://glin.github.io/reactable
Other
627 stars 80 forks source link

How to add colour to text in specific cells ? [question] #252

Closed JauntyJJS closed 2 years ago

JauntyJJS commented 2 years ago

Hi

I have a data set like this

initialisation_data <- data.frame(
  SBP = c(-3, -0.5, -1, 1, 1, -0.5),
  DBP = c(1, -2, 0, 1, 2, 4)
)

Created on 2022-07-08 by the reprex package (v2.0.1)

initialisation_data %>%
  reactable::reactable(defaultPageSize = 6)

and I wish to change the colour of these numbers in the specific cells to a different colour

image

Is there a way to do this with reactable. So far the examples, I have seen are complex colour scaling of a column.

The reason I want to do it is because these position used to be missing values and I want to emphasize what they have been replaced with.

image

glin commented 2 years ago

Hi, you might be able to do this with the index argument in the conditional styling functions: https://glin.github.io/reactable/articles/conditional-styling.html#cell-r-functions

The docs could probably use more examples of this, but here's one example in the Cookbook where specific rows have been highlighted based on their row index: https://glin.github.io/reactable/articles/cookbook/cookbook.html#highlight-rows

Or a quick cell styling example using your example data, adding a yellow background to SBP column cells in rows 2 and 6:

initialisation_data <- data.frame(
  SBP = c(-3, -0.5, -1, 1, 1, -0.5),
  DBP = c(1, -2, 0, 1, 2, 4)
)

reactable::reactable(
  initialisation_data,
  columns = list(
    SBP = colDef(
      style = function(value, index) {
        if (index %in% c(2, 6)) {
          list(background = "yellow")
        }
      }
    )
  )
)

You can swap out c(2, 6) with the indices of the NAs.

If all your columns are the same, you could also use a default column definition to cut down on repeated code. Conditional style functions have a name argument as well to get the current column name. Here's an untested example of what that might look like:

reactable::reactable(
  initialisation_data,
  defaultColDef = colDef(
    style = function(value, index, name) {
      missing_indices <- which(is.na(missing_data[[name]]))
      if (index %in% missing_indices) {
        list(background = "yellow")
      }
    }
  )
)
JauntyJJS commented 2 years ago

Thank you. It works perfectly.