Reputation: 123
I would like to take a gt() table and transform it to a "wide" format instead of a "long" format by group level. So for, as an example using the iris data set:
library(dplyr)
library(gt)
iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
gt()
This produces:
However, what I want to produce is the following:
Is there a way to do this?
Upvotes: 7
Views: 1774
Reputation: 93821
We can do this with a combination of data reshaping and gt
formatting functions. I've also reformatted the column names to remove periods and put them in title case.
library(tidyverse)
library(gt)
iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value) %>%
select(-row) %>%
gt() %>%
tab_spanner_delim(
delim="_"
) %>%
fmt_missing(
columns=everything(),
missing_text=""
)
Upvotes: 6