Search code examples
rgt

Embed links to cells of R's gt tables


I wish to use the gt library to create HTML tables from csv files. In some cells I wish to combine text and a hyperlink. Something like:

Here is a link to the BBC

I found an example of how to include a link, but am unsure as to how to combine this with text.

# Src: https://community.rstudio.com/t/create-interactive-links-in-gt-table-in-rmarkdown/70266

library("tidyverse")
library("gt")

df <- tibble(
  name = c("BBC", "CNN"),
  link = c("https://www.bbc.com/news", "https://edition.cnn.com/")
  )

# Creates a single link
df %>%
  mutate(
    link = map(link, ~ htmltools::a(href = .x, "website")),
    link = map(link, ~ gt::html(as.character(.x)))) %>%
  gt()

# Something like this would be nice
df <- tibble(
  name = c("BBC", "CNN"),
  link = c("Here is a [link](https://www.bbc.com/news) to the BBC", "And [here](https://edition.cnn.com/) is a link to CNN")
)

Solution

tibble(
  name = c("BBC", "CNN", "GA"),
  link = c("Here is a <a href = 'https://www.bbc.com/news'>link</a> to the BBC", 
           "And <a href = 'https://edition.cnn.com/'>here</a> is a link to CNN",
           "And here is no link")
) %>%
  mutate(link = map(link, gt::html)) %>%
  gt |> 

Need to add this or text in column will be centered

cols_align( align = c("left"), columns = everything() )

Image from RStudio Viewer enter image description here


Solution

  • You can use -

    library(tidyverse)
    library(gt)
    
    df <- tibble(
      name = c("BBC", "CNN"),
      link = c("https://www.bbc.com/news", "https://edition.cnn.com/")
    )
    
    df %>%
      mutate(link = sprintf('<p>Here is a link to <a href = "%s">%s</a> website', link, name), 
             link = map(link, gt::html)) %>%
      gt()
    

    enter image description here


    To do this manually with different text you can do -

    tibble(
      name = c("BBC", "CNN"),
      link = c("Here is a <a href = 'https://www.bbc.com/news'>link</a> to the BBC", 
               "And <a href = 'https://edition.cnn.com/'>here</a> is a link to CNN")
      ) %>%
      mutate(link = map(link, gt::html)) %>%
      gt