Skip to content

data_color() strips column attributes #637

@Torvaney

Description

@Torvaney

Hello,

I have been using gt to generate tables showing data for a few different metrics. The columns showing these metrics must meet some quite specific requirements:

  • The table text should show the metric's value
  • The cell colours should be scaled to the metric's percentile value (calculated within a much larger sample than is shown in the table)

I have been working around this by "hiding" the percentiles as metadata in the metric's attributes, and composing a colour scaling function with a percentile-getter to scale the colours appropriately. See the example below:

library(tidyverse)
library(gt)

# Generate some example data where the percentile is calculated on a superset
example_data <- 
  tibble::tibble(group = sample(letters, 500L, replace = TRUE),
                 metric_value = rnorm(500L)) %>% 
  mutate(metric_percentile = percent_rank(metric_value)) %>% 
  filter(group == "a")

# Hide the percentiles as attributes
example_data_percentiled <- 
  example_data %>% 
  transmute(group, 
            metric_value_with_percentile = structure(
              metric_value,
              percentiles = metric_percentile,
              class = c("vector_with_percentiles", class(metric_value))
            ))


gt(example_data_percentiled) %>% 
  data_color(
    columns = vars(metric_value_with_percentile),
    colors = compose(
      scales::col_numeric(
        palette = c("white", "green"),
        domain  = c(0, 1)),
      function(x) attr(x, "percentiles"))
  ) 

However, with v0.2.2, this no longer works. Specifically, due to the changes introduced by this commit:

# Before
data_vals <- data_tbl[[column]]

# After
data_vals <- data_tbl[[column]][rows]

By selecting the rows in this way, the attributes of any column are stripped out. This makes us unable to execute a hack workaround such as this one.

I don't think this specific change to gt should necessarily be reversed (this is an exceptionally niche use-case); although it would be nice to be able to map a columns colour to data in other columns.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions