Using a portion of the towny dataset, let’s create a gt table. We can use fmt_url() 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 (cols_merge() 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" )
fmt_url() 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. fmt_url() 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()
Links can be presented as icons. Let’s take a look at an example of this type of presentation with a table based on the films dataset. The imdb_url column contains the URL information and in the fmt_url() call, we can use fontawesome::fa() to specify a label. In this case we elect to use the "link" icon and we can make some sizing adjustments to the icon here to ensure the layout looks optimal. We also use cols_merge() to combine the film’s title, its original title (if present), and the link icon.