I have a gt table that has a series of spanners. Each spanner has two columns beneath it. I'd like to format it such that the columns under every other spanner are highlighted. Columns 1 has the stub values. In the code below, column 2 is the location of the first column under Spanner 1. I would expect column 3 to highlight the column directly next to 2, but instead it skips that column and highlights the first column of the second spanner (what I would call column 4).
my_data %>%
gt() %>%
tab_spanner_delim(delim = "_") %>%
tab_style(
style = list(cell_fill(color = "#f2dddc")),
locations = cells_body(columns = c(2,3)) # 6,7,10,11, etc. for every other spanner
)
So how do I format my code to reference both columns under a spanner/how do I reference any column under a spanner that isn't the first column? Is there a way to reference the spanner as the location reference?
And for what it's worth, I'm doing this within Shiny, so once I understand the mechanics of gt() I will need to further modify the code to make it dynamic.
Thank you!
Update: I'm having similar issues with referencing spanners. The code below successfully adds a left border starting from the spanner and running to the bottom of the column on columns 2 and 3 (so the first spanner and its 2 columns are wrapped in outer borders).
%>%
tab_style(
style = list(cell_borders(
sides = "left",
color = "black",
weight = px(3)
)),
locations = list(cells_column_labels(columns = c(2,3)), #left side of column two and 3 (remember col 3 is the first column of spanner 2)
cells_body(columns = c(2,3)), #Repeat of above but with the column values
cells_column_spanners(spanners = c(1,2)) #Left sides of spanners 1 and 2 (left side of spanner 2 = left side of col 3)
)) #Results are as expected
Now, I want to highlight the name of the first spanner. Given the code chunk above, it makes sense to me to reference spanner 1. When I reference spanner 1, the second spanner is highlighted. Any idea why? I don't understand why I can get a border to the left of spanner 1 by referencing '1', but when I make the same spanner reference to highlight the cell, it highlights spanner 2. I then tried referencing spanner 0 and it threw an error that the indice didn't exist.
%>%
tab_style(
style = list(
cell_fill(color = "#f2dddc")),
locations = list(cells_column_spanners(
spanners = 1)) #Why does this line highlight spanner 2?
)
I've come to realize that the (my) confusion lies in the tab spanner delimiter. I used pivot_wider to prepare my data for gt() resulting in a df formatted as such: (1) Group1_varA, (2) Group2_varA, (3) Group3_varA, (4) Group1_varB, (5) Group2_varB, (6) Group2_varB.
The tab_spanner_delimiter rearranges the columns so varA and VarB are under their respective groups, but the column indices don't change, making the column orders in the above example 1,4,2,5,3,6.