
This is my current code
library(palmerpenguins)
library(gt)
penguins_no_na <- na.omit(penguins)
penguins_no_na |>
gt(groupname_col = c("species","island"))
I am trying to present Penguin's data formatted using the gt package for PDF documents. I would like to group the data by species and then by island column on the table.
My code is giving me variables from columns species and island on the same row. I cannot work out how to make it show variables from species and island on separate rows, variables from species above variables from the island. For example, for the Adelie species on Torgersen Island, I would like to show Adelie on one row and then Torgersen on the row below Adelie.
I also would like to make the text bold each of the species and each of the islands in bold with the background color yellow for species variables and blue for island variables and text color in black, if possible. Any help is appreciated.
I am trying to achieve this:
With more googling I managed to write this code
row_group_sep <- " - " # Default row_group.sep
penguins_no_na %>%
gt(rowname_col = "sex", groupname_col = c("species", "island")) %>%
gt::text_transform(
locations = cells_row_groups(),
fn = function(x) {
lapply(x, function(x) {
x <- strsplit(x, split = row_group_sep)[[1]]
if (length(x) > 1) {
return(gt::md(paste0("**", paste(x, collapse = "** - **"), "**")))
} else {
return(gt::md(paste0("**", x, "**")))
}
})
}
) |>
tab_style(
style = list(
cell_fill(color = "yellow"),
cell_text(color = "black")
),
locations = cells_row_groups())
which achieves the below:
I would still like show them on separate rows, for example Adelie on one row then Torgersen on row below.

