在带有html输出的R markdown文档中,我可以创建带有标题和图像的标签,如下所示:
```{r}
print.img <- function(img, caption = ''){
cat('')
}
folder <- '/Users/U77549/Desktop/'
require(magrittr)
```
## Some Tabs
###{.tabset}
#### Tab 1
```{r, results = 'asis'}
paste0(folder, 'a', '.png') %>% print.img
```
#### Tab 2
```{r, results = 'asis'}
paste0(folder, 'b', '.png') %>% print.img
```
Run Code Online (Sandbox Code Playgroud)
但是,如果我想迭代生成一堆标签怎么办?这是我的尝试。
```{r }
make.tabs <- function(title, image){
catx <- function(...) cat(..., sep = '')
for(i in seq_along(title)){
catx('#### ', title[i], '\n')
catx("```{r, results = 'asis'}", '\n')
catx("paste0(folder, '", image[i], "', '.png') %>% print.img", '\n')
catx('```', '\n\n')
}
}
```
## Some Tabs
###{.tabset}
```{r, results = 'asis'}
make.tabs(title = c('Tab 1', 'Tab 2'), image = c('a', 'b'))
```
Run Code Online (Sandbox Code Playgroud)
但这是行不通的。除了实际显示图像外,它仅显示{r, results = 'asis'} paste0(folder, 'a', '.png') %>% print.img在选项卡中。有没有办法使这项工作?
这不起作用,因为knit只传递一次代码来解释它。按照你的写作方式,你需要编织两次。第一次创建新块,第二次运行这些新块。仅使用一个文件这是不可能的。相反,您可能想要使用普通的 R 脚本来构建要编织的 Rmd。
创建 Rmd 进行渲染的经典R文件:
# Function to create multiple tabs
make.tabs <- function(title, image){
res <- NULL
for(i in seq_along(title)){
res <- c(res, '#### ', title[i], '\n',
"```{r, results = 'asis'}", '\n',
"paste0(folder, '", image[i], "', '.png') %>% print.img", '\n',
'```', '\n\n')
}
return(res)
}
# Create the Rmd to knit
cat(
'---
title: "Untitled"
author: "author"
date: "2017-10-23"
output: html_document
---
## Some Tabs
###{.tabset}
```{r}
library(dplyr)
```
',
make.tabs(title = c('Tab 1', 'Tab 2'), image = c('a', 'b')),
sep = "",
file = "filetoknit.Rmd")
# Render the Rmd created into html here
rmarkdown::render("filetoknit.Rmd")
Run Code Online (Sandbox Code Playgroud)
这是创建的输出 Rmd 文件 (filetoknit.Rmd):
---
title: "Untitled"
author: "author"
date: "2017-10-23"
output: html_document
---
## Some Tabs
###{.tabset}
```{r}
library(dplyr)
```
#### Tab 1
```{r, results = 'asis'}
paste0(folder, 'a', '.png') %>% print.img
```
#### Tab 2
```{r, results = 'asis'}
paste0(folder, 'b', '.png') %>% print.img
```
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1665 次 |
| 最近记录: |