我对此进行了一些实验,以下是我能想到的最好的。这是一个完整的 Markdown 文档,您应该可以将其粘贴到 RStudio 中并点击 Knit 按钮。
这里有两个相关的说明。
- 将文件链接直接设置为 kable 不起作用,因为它被包装在 html 中,因此它被解释为文本,因此我们需要将其
gsub() 它。另一种方法是设置 kable(..., escape = FALSE),但它是其他文本可能会导致问题的风险。
- 此外,块选项
results = 'asis' 是使 print(kab) 返回原始 html 所必需的。
我不知道这些是不是实际应用的问题。
---
title: "Untitled"
author: "me"
date: "02/06/2020"
output: html_document
---
```{r, results = 'asis'}
library(ggplot2)
library(svglite)
n <- length(unique(iris$Species))
data <- split(iris, iris$Species)
# Create list of plots
plots <- lapply(data, function(df) {
ggplot(df, aes(Sepal.Width, Sepal.Length)) +
geom_point()
})
# Create temporary files
tmpfiles <- replicate(n, tempfile(fileext = ".svg"))
# Save plots as files, get HTML links
links <- mapply(function(plot, file) {
# Suit exact dimensions to your needs
ggsave(file, plot, device = "svg", width = 4, height = 3)
paste0('<figure><img src="', file, '" style = "width:100%"></figure>')
}, plot = plots, file = tmpfiles)
# Table formatting
tab <- data.frame(name = names(plots), fig = paste0("dummy", LETTERS[seq_len(n)]))
kab <- knitr::kable(tab, "html")
# Substitute dummy column for figure links
for (i in seq_len(n)) {
kab <- gsub(paste0("dummy", LETTERS[i]), links[i], kab, fixed = TRUE)
}
print(kab)
```