使用循环在R markdown中生成制表符

在带有html输出的R markdown文档中,我可以创建标题和图像的标签,如下所示:

```{r}
print.img <- function(img, caption = ''){
 cat('![', caption,   '](', img, ')')
}
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
```

但是,如果我想迭代生成一堆标签怎么办?这是我的尝试.

```{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'))
```

但这不起作用.而不是实际显示图像,它只显示例如选项卡中的{r,results =’asis’} paste0(文件夹,’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")

这是创建的输出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
```
点赞