首页 > 解决方案 > 嵌入到 R 的 gt 表的单元格的链接

问题描述

我希望使用 gt 库从 csv 文件创建 HTML 表。在某些单元格中,我希望将文本和超链接结合起来。就像是:

这是BBC的链接

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

# 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 查看器的图像 在此处输入图像描述

标签: rgt

解决方案


您可以使用 -

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

推荐阅读