jthomasmock / gtExtras

A Collection of Helper Functions for the gt Package.
https://jthomasmock.github.io/gtExtras/
Other
193 stars 26 forks source link

gt_color_rows using "type" columns #50

Closed 5plusspieldauer closed 2 years ago

5plusspieldauer commented 2 years ago

I noticed that some code I had working for one dataframe didn't work for another with slightly different column names. Turns out it was because one of column names was "type".

tibble("name"=c("A", "B", "C"), type = c("a", "b", "c"), value=c(0.1, 0.6, 0.9)) %>% gt() %>% gt_color_rows(value)

throws up the error "Error in match.arg(type) : 'arg' must be of length 1" which seems to be because it pulls the type argument for the palette from the type in column in my df.

Since "type" isn't an uncommon column name, I'd suggest either disabling pulling the type from table or naming it something less frequent, like "scale_type", etc.

Love the package, btw, keep up the great work!

jthomasmock commented 2 years ago

Interesting!

So this behavior is present in gt itself. 🤔

I think gt::data_color() is a bit too aggressive in evaluating type outside of the local environment. I've gone ahead and converted type arg to pal_type, but will open another issue in gt proper.

library(gt)

base_gt <- dplyr::tibble(
  "name" = c("A", "B", "C"),
  type = c("a", "b", "c"), 
  value = c(0.1, 0.6, 0.9)
) %>%
  gt()

# type is not present in the env
type
#> Error in eval(expr, envir, enclos): object 'type' not found

# evaluates type from the underlying dataframe
base_gt %>% 
  data_color(
    columns = value,
    colors = scales::col_numeric(
      palette = 
        paletteer::paletteer_d(
          palette = "ggsci::red_material",
          type = type
        ) %>% as.character(),
      domain = c(0,1)
    )
  )
#> Error in match.arg(type): 'arg' must be of length 1

# allows for operations on type, where type == "a"
# so it throws an error not matching discrete or continuous

base_gt %>% 
  data_color(
    columns = value,
    colors = scales::col_numeric(
      palette = 
        paletteer::paletteer_d(
          palette = "ggsci::red_material",
          type = type[1]
        ) %>% as.character(),
      domain = c(0,1)
    )
  )
#> Error in match.arg(type): 'arg' should be one of "discrete", "continuous"

Created on 2022-05-23 by the reprex package (v2.0.1)