使用循环在R markdown中生成选项卡

5
在具有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(folder, 'a', '.png') %>% print.img,而不是实际显示图像。有没有办法让它工作?

1个回答

4

这个方法不起作用是因为knit只会一次性地解释你的代码。按照你的写法,你需要运行两次knit。第一次是为了创建新的代码块,第二次是运行这些新的代码块。但是在同一个文件中无法实现这一点。相反,您可以使用普通的R脚本来构建您的Rmd以进行编织。

传统的R文件创建Rmd以呈现:

# 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
```

我默认有数字标签,如何使选项卡不带编号? - yuliaUU
你可以在标题后面加上 {-} 使其不带编号。 - Sébastien Rochette

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接