rstudio / gt

Easily generate information-rich, publication-quality tables from R
https://gt.rstudio.com
Other
2.02k stars 205 forks source link

cols_width() is off by one column when row_group.as_column = TRUE #1253

Closed joranE closed 3 months ago

joranE commented 1 year ago

Description

Column selections in cols_width() are shifted one column to the left when creating a grouped table and setting row_group.as_column = TRUE.

Reproducible example

library(gt)
library(dplyr)

# Example includes column borders via tab_style() to make is easy to see which columns are changing size

# Makes the hp column very wide, as expected
mtcars %>%
  select(cyl,mpg,hp) %>%
  gt() %>%
  tab_style(
    style = cell_borders(),
    locations = cells_body(
      columns = everything(),
      rows = everything()
    )
  ) %>%
  cols_width(hp ~ px(200))

# With a grouped table, still correctly makes the hp column very wide
mtcars %>%
  select(cyl,mpg,hp) %>%
  group_by(cyl) %>%
  gt() %>%
  tab_style(
    style = cell_borders(),
    locations = cells_body(
      columns = everything(),
      rows = everything()
    )
  ) %>%
  tab_options(row_group.as_column = FALSE) %>%
  cols_width(hp ~ px(200))

# When we set row_group.as_column = TRUE, now the mpg column
# is very wide and the hp column is unchanged
mtcars %>%
  select(cyl,mpg,hp) %>%
  group_by(cyl) %>%
  gt() %>%
  tab_style(
    style = cell_borders(),
    locations = cells_body(
      columns = everything(),
      rows = everything()
    )
  ) %>%
  tab_options(row_group.as_column = TRUE) %>%
  cols_width(hp ~ px(200))

Expected result

When setting row_group.as_column = TRUE, column selections in cols_width() should apply to the selected columns, not the one to the immediate left.

Session info

> sessionInfo()
R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Monterey 12.0.1

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_1.1.0 gt_0.8.0   

loaded via a namespace (and not attached):
 [1] rstudioapi_0.14  magrittr_2.0.3   tidyselect_1.2.0 munsell_0.5.0    colorspace_2.1-0
 [6] R6_2.5.1         rlang_1.0.6      fastmap_1.1.1    fansi_1.0.4      tools_4.2.2     
[11] grid_4.2.2       gtable_0.3.1     utf8_1.2.3       cli_3.6.0        withr_2.5.0     
[16] htmltools_0.5.4  digest_0.6.31    tibble_3.2.0     lifecycle_1.0.3  ggplot2_3.4.1   
[21] sass_0.4.5       vctrs_0.5.2      glue_1.6.2       compiler_4.2.2   pillar_1.8.1    
[26] generics_0.1.3   scales_1.2.1     pkgconfig_2.0.3 
ian-curtis commented 1 year ago

Can also confirm this bug when using row_group.as_column = TRUE. Consider this one upvote from me!