如何在Rmarkdown中向表添加一个fontawesome图标?

时间:2018-11-30 00:42:12

标签: r r-markdown knitr font-awesome bookdown

我正在寻找一种整洁的方法,将包含字体图标的超链接添加到Rmarkdown表(电缆)中-以便合并到html bookdown页面中。

在文档的其他部分,我使用了icon包,使用标准的markdown语法(例如:

)来渲染超链接的字体图标(在表格外部)。
`r icon::fa("file-pdf", size = 5)](https://www.google.com/){target="_blank"}`

enter image description here

但是当我尝试将其合并为kable的一部分时,这种方法不起作用。

```{r}

library(icon)
library(knitr)
library(tidyverse)

## note this code throws the following error: Error in 
## as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = 
## stringsAsFactors) : cannot coerce class "c("knit_asis", 
## "knit_icon")" to a data.frame

link_location <- "www.google.com"

data_test_1 <- data.frame(
  file = c('Version 1', 'Version 2', 'Version 3'),
  last_updated = Sys.Date(),
  pdf_logo = icon::fa("file-pdf")) %>%
  mutate(pdf_logo = cell_spec(pdf_logo,
    link = link_location)) %>%
  kable("html", escape = F, align = "c")
data_test_1
```

到目前为止,我已经提出了一种解决方法,其中涉及从fontawesome网站下载.svg文件并将其添加为图像。它的工作原理是……,但我希望能够更改图标的大小,并使其更易于再现。

这是我当前解决方法的代码。

```{r fontawesome_table ='asis'}

library(tidyverse)
library(kableExtra)

## download svg from location manually
https://fontawesome.com/icons/r-project?style=brands

data_test_2 <- data.frame(
  file = c('Version 1', 'Version 2', 'Version 3'),
  last_updated = Sys.Date(),
  R_logo = "![](r-project-brands.svg)") %>%
  mutate(R_logo = cell_spec(R_logo, link = "https://cran.r- 
  project.org/")) %>%
  kable("html", escape = F, align = "c")
data_test_2
```

哪个产生此输出...

Output produced by chunk above

有人对我如何调整表中图标的大小或从另一个软件包/ css中调用该图标以创建更整洁的解决方案有任何想法吗?

1 个答案:

答案 0 :(得分:2)

这里是使用fontawesome包的一种方式。我还必须使用自定义链接构建功能:

```{r, echo = F, message=F, warning=F}
library(fontawesome)
library(knitr)
library(tidyverse)
library(kableExtra)
## note this code throws the following error: Error in 
## as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = 
## stringsAsFactors) : cannot coerce class "c("knit_asis", 
## "knit_icon")" to a data.frame

link_location <- "www.google.com"

addLink <- function() {
  paste0("<a href=\"", link_location, "\">", as.character(fa("file-pdf")), "</a>")
}

data_test_1 <- data.frame(file = c('Version 1', 'Version 2', 'Version 3'),
                          last_updated = Sys.Date(),
                          pdf_logo = addLink())

kable(data_test_1, escape = F, align = "c")
```

enter image description here

相关问题