要定义rmd 文件之外的链接,您可以使用parameterized report。这允许您在编译时将值传递到rmarkdown 文档中。为此,首先创建一个包含所需参数的rmarkdown 文档,这些参数在yaml 标头中声明,然后在报告中稍后使用。然后,在单独的 R 脚本中,运行 render 命令(来自 rmarkdown 包)并传递所需的参数值。
这是一个使用cat 或paste 生成链接的示例。为了比较,我还添加了第二组参数,这些参数使用@JohnCoene 答案中的方法添加不同的链接。我已将rmarkdown 文档保存为"test.rmd",这是在render 命令中识别该文档的方式。
rmarkdown文档
---
output: html_document
params:
text1: "add text"
link1: "add URL"
text2: "add text"
link2: "add URL"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
# Function to add link
myFun <- function(text, link, inline=TRUE) {
if(inline) {
paste("[", text, "](", link, ")", sep="")
} else {
cat("[", text, "](", link, ")", sep="")
}
}
```
Blah, blah, blah, more text. And here's the link:
```{r, results="asis"}
myFun(params$text1, params$link1, inline=FALSE)
```
Blah, blah, blah, more text. And here's a way to `r myFun(params$text1, params$link1)`.
Or, using the examples from `@JohnCoene's` answer:
With an HTML tag:
```{r, results="asis"}
tg <- function (link, text){
paste0("<a href='", link, "'>", text, "</a>")
}
tg(params$link2, params$text2)
```
With `htmltools`:
```{r}
# install.packages("htmltools")
library(htmltools)
tags$a(
href = params$link2,
params$text2
)
```
单独的 R 脚本来渲染 rmarkdown 文档
library(rmarkdown)
render(input="test.rmd",
params=list(text1="link to Stackoverflow",
link1="https://stackoverflow.com/questions/52745926/r-markdown-hyperlink-outside-rmd-file",
text2="link to google",
link2="https://google.com"))
输出的 html 文档如下所示: