Use the towny dataset to create a gt table. After some major dplyring to get a nicely formatted data table, we use the fmt_url() function on the website column to generate navigable links to websites. By default the links are underlined and the color will be chosen for you (it’s dark cyan).
towny |> dplyr::filter(csd_type =="city") |> dplyr::arrange(desc(population_2021)) |> dplyr::select(name, website, population_2021) |> dplyr::slice_head(n =10) |>gt() |>tab_header(title =md("The 10 Largest Municipalities in `towny`"),subtitle ="Population values taken from the 2021 census." ) |>fmt_integer() |>fmt_url(columns = website) |>cols_label(name ="Name",website ="Site",population_2021 ="Population" )
Let’s try something else. We can set a static text label for the link with the label argument (and we’ll use the word "site" for this). The link underline is removable with show_underline = FALSE. With this change, it seems sensible to merge the link to the "name" column and enclose the link text in parentheses (the cols_merge() function handles all that).
towny |> dplyr::filter(csd_type =="city") |> dplyr::arrange(desc(population_2021)) |> dplyr::select(name, website, population_2021) |> dplyr::slice_head(n =10) |>gt() |>tab_header(title =md("The 10 Largest Municipalities in `towny`"),subtitle ="Population values taken from the 2021 census." ) |>fmt_integer() |>fmt_url(columns = website,label ="site",show_underline =FALSE ) |>cols_merge(columns =c(name, website),pattern ="{1} ({2})" ) |>cols_label(name ="Name",population_2021 ="Population" )
The fmt_url() function allows for the styling of links as ‘buttons’. This is as easy as setting as_button = TRUE. Doing that unlocks the ability to set a button_fill color. This color can automatically selected by gt (this is the default) but here we’re using "steelblue". The label argument also accepts a function! We can choose to adapt the label text from the URLs by eliminating any leading "https://" or "www." parts.
It’s perhaps inevitable that you’ll come across missing values in your column of URLs. The fmt_url() function will preserve input NA values, allowing you to handle them with sub_missing(). Here’s an example of that.
towny |> dplyr::arrange(population_2021) |> dplyr::select(name, website, population_2021) |> dplyr::slice_head(n =10) |>gt() |>tab_header(title =md("The 10 Smallest Municipalities in `towny`"),subtitle ="Population values taken from the 2021 census." ) |>fmt_integer() |>fmt_url(columns = website) |>cols_label(name ="Name",website ="Site",population_2021 ="Population" ) |>sub_missing()