Create interactive links in gt table (in rmarkdown)

Hello,

Is it possible to create a gt table in an rmarkdown document which includes weblinks which can be clicked? I have seen the html() helpers (https://gt.rstudio.com/reference/html.html), but fail to understand how this can be used for the content of a cell.

Many thx!

library(tidyverse)
library(gt)

df <- data.frame(
  stringsAsFactors = FALSE,
           country = c("UK", "US"),
              name = c("BBC", "CNN"),
              link = c("https://www.bbc.com/news", "https://edition.cnn.com/")

df %>%
gt()

You can use the gt helpers to format html or md content inside a table

Example

library(gt)
library(tidyverse)

df <- tibble(
  country = c("UK", "US"),
  name = c("BBC", "CNN"),
  link = c("https://www.bbc.com/news", "https://edition.cnn.com/"))
  
# using html
df %>%
    mutate(
        link = map(link, ~ htmltools::a(href = .x, "website")),
        link = map(link, ~ gt::html(as.character(.x)))) %>%
    gt()

country

name

link

UK

BBC

website

US

CNN

website


# using markdown
df %>%
    mutate(
        link = glue::glue("[website]({link})"),
        link = map(link, gt::md)) %>%
    gt()

country

name

link

UK

BBC

website

US

CNN

website

Created on 2020-06-18 by the reprex package (v0.3.0.9001)

  • html() will tell gt to deal with the text as html content. You can create the text yourself. I used htmltools helper
  • md() will tell get to consider the text as markdown, and it will process it to render as html.

Hope it helps

3 Likes

One possibility to do this is shown in the code below:
when formatting the link column convert the url to a hyperlink to that url with the same reference text.
We can do that by using the fmt function to format the link column with the make_hyperlink function.

Knitting the following Rmd file

---
title: "Untitled"
author: "My name"
date: "6/18/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(gt)

make_hyperlink = function(myurl,mytext=myurl) {
  paste('<a href="',myurl,'">',mytext,'</a>')
}

df <- data.frame(
  stringsAsFactors = FALSE,
           country = c("UK", "US"),
              name = c("BBC", "CNN"),
              link = c("https://www.bbc.com/news", "https://edition.cnn.com/")
)

df %>%
gt() %>%
  fmt (
    columns = 'link',
    fns = make_hyperlink
  )
```

creates a html document with the code (not shown here) and the following table:

image

3 Likes

@cderv: will check out your functions :grinning:

This is an equivalent solution. On my side, I modified the table before applying gt() but you modify only at the formatting stage when building the table. Clever! I find the your formatting function simpler and clever !
Thanks for sharing !

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.