嵌入链接到 R 的 gt 表的单元格

Embed links to cells of R's gt tables

我希望使用 gt 库从 csv 文件创建 HTML 表。在某些单元格中,我希望结合文本和 hyperlink。类似于:

这里是 link 给 BBC

我找到了一个如何包含 link 的示例,但不确定如何将其与文本相结合。

# 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")
)

解决方案

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 |> 

需要添加此项,否则列中的文本将居中

cols_align( 对齐 = c("左"), 列 = 一切() )

图片来自 RStudio 查看器

您可以使用-

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()


要使用不同的文本手动执行此操作,您可以执行 -

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