Naming R code chunks in knitr

Hi, I'm trying to use knitr and rmarkdown. I'd like to generate chunk names via R expressions. For example, I have a variable, call it foo, that changes values in one or more code chunks. How can I use that variable foo to name a R code chunk?

I've tried the following in a Rmd file:

foo <- 2
plot(1:4)
foo <- 10
plot(1:4)

When I try to knit an rmarkdown file containing the above code, I get an error about having a duplicate label.

processing file: Untitled.Rmd
Error in parse_block(g[-1], g[1], params.src) :
duplicate label 'paste0("plot-",foo)'
Calls: ... process_file -> split_file -> lapply -> FUN -> parse_block
Execution halted

How can I create chunk labels that use the distinct values of the variable foo?

Is there a way to have R evaluate the expression that gets passed to label?

Here is the full text of my Untitled.Rmd file:


---
title: "Untitled"
author: "Frederick Boehm"
date: "8/1/2019"
output: html_document
---

```{r setup}
foo <- 2
```

```{r label = paste0("plot-", foo)}
plot(1:4)
foo <- 10
```

```{r label = paste0("plot-", foo)}
plot(1:4)
```
1 Like

Welcome to RStudio Community!

I don't think this is possible. The chunk names are evaluated before any of the code is executed. Even if you only use one chunk (to avoid the duplicate chunk name issue), the chunk name is paste0("plot-", foo), not plot-2.

See the responses to this related question on StackOverflow for potential workarounds.

1 Like

Thank you, @jdblischak! The StackOverflow discussion is very helpful!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.