【问题标题】:Embed links to cells of R's gt tables嵌入到 R 的 gt 表的单元格的链接
【发布时间】:2021-08-11 00:08:01
【问题描述】:

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

这是 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 查看器的图像

【问题讨论】:

    标签: r gt


    【解决方案1】:

    你可以使用 -

    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
    

    【讨论】:

    • 我不确定是不是这样。文本和链接以不同方式组合在 csv 文件中。 “这是一个链接到 BBC”和“而这里是一个到 CNN 的链接”
    • 我展示了如何做到这一点的基本概念。您也可以使用不同的文本手动执行此操作。请参阅我的更新答案。
    • 谢谢。我得到它。我注意到 gt::html 似乎使所有文本居中。如何保持左对齐?
    • 是这样吗?我认为中心不合理。
    • 我将您的解决方案和居中链接列的图像添加到原始问题中。
    猜你喜欢
    • 2021-05-29
    • 2016-01-04
    • 2023-01-21
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多