jthomasmock / gtExtras

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

`gt_index()` doesn't handle multiple group labels #58

Closed jmbarbone closed 2 years ago

jmbarbone commented 2 years ago

Hitting an error in gt_index() (through gt_plt_conf_int()) that isn't anticipating multiple group labels

library(gtExtras)
df <- data.frame(
  row = 1:4,
  group1 = c("a", "a", "b", "b"),
  group2 = c("c", "d", "c", "d"),
  ci = c(2, 2, 4, 6),
  lower = c(1, 1, 2, 2),
  upper = c(6, 6, 8, 8)
)

df %>% 
  gt::gt("row", c("group1", "group2")) %>%
  gt_plt_conf_int(ci, c(lower, upper))
#> Error in `rlang::sym()`:
#> ! Can't convert a character vector to a symbol.

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

Traced it back to this rlang::sym() call from gt_index() -- character vector with both (all) group labels is passed and rlang::sym() doesn't like multiple length vectors.

https://github.com/jthomasmock/gtExtras/blob/ddcc292d08cc89c6d8a079f2e50f68698a9d6706/R/gt_index.R#L86-L89

jthomasmock commented 2 years ago

Thanks for the prompt and nice reprex!

I believe this is working now in the latest version.

library(gtExtras)
df <- data.frame(
  row = 1:4,
  group1 = c("a", "a", "b", "b"),
  group2 = c("c", "d", "c", "d"),
  ci = c(2, 2, 4, 6),
  lower = c(1, 1, 2, 2),
  upper = c(6, 6, 8, 8)
)

df %>% 
  gt::gt("row", c("group1", "group2")) %>%
  gt_plt_conf_int(ci, c(lower, upper))

Created on 2022-06-25 by the reprex package (v2.0.1)

gt_index() alone

I've also done some testing against random row ordering and it appears to be valid for multi groups.

library(dplyr,w=F)

confirm_gt_df <- function(seed = sample(1:10000, size = 1)){

  withr::with_seed(
    seed = seed, 
    code = {
      df <- mtcars |> 
        mutate(row_n = row_number()) |> 
        group_by(am, cyl) |> 
        slice_sample(n = 2)

      tab <- gt::gt(df)

      tab_in <- gtExtras::gt_index(tab, as_vector = FALSE)

      cat(all.equal(arrange(df, am, cyl) |> ungroup(), tab_in), seed, "\n")

      }

    )
}

for(i in 1:25){
  confirm_gt_df()
}
#> TRUE 3309 
#> TRUE 5464 
#> TRUE 3268 
#> TRUE 3825 
#> TRUE 5715 
#> TRUE 1921 
#> TRUE 8910 
#> TRUE 184 
#> TRUE 6598 
#> TRUE 1060 
#> TRUE 9149 
#> TRUE 8168 
#> TRUE 1780 
#> TRUE 9707 
#> TRUE 2006 
#> TRUE 5694 
#> TRUE 8396 
#> TRUE 1941 
#> TRUE 5711 
#> TRUE 3576 
#> TRUE 4862 
#> TRUE 2754 
#> TRUE 8308 
#> TRUE 3019 
#> TRUE 5897

Created on 2022-06-25 by the reprex package (v2.0.1)

jthomasmock commented 2 years ago

@jmbarbone - let me know if you run into further issues - thanks!