Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating tabs in R markdown with a loop

Tags:

In an R markdown document with html output, I can create tabs with titles and images like this:

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

But what if I want to generate a bunch of tabs iteratively? Here's my attempt.

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

But that doesn't work. Instead of actually showing the image it only displays e.g. {r, results = 'asis'} paste0(folder, 'a', '.png') %>% print.img in the tab. Is there a way to make this work?

like image 732
IceCreamToucan Avatar asked Oct 22 '17 18:10

IceCreamToucan


1 Answers

This does not work because knit only passes once on your code to interpret it. In your way of writing, you need to knit two times. A first time to create the new chunks and a second time to run these new chunks. This is not possible with only one file. Instead, you may want to use a normal R-script that will build your Rmd to knit.

The classical R file that creates a Rmd to render:

# 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")

Here is the output Rmd file created (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
```
like image 200
Sébastien Rochette Avatar answered Sep 30 '22 00:09

Sébastien Rochette