Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get chunk name in knitr?

I want to set the chunk option "eval" based on a list of chunk names. Is there a function to get the chunk name in knitr, e.g. chunk_name?

This is my minimum example with fake function name "chunk_name".

---
output: html_document
---

```{r setup}
eval_chunks <- c('chunk1')
```

```{r chunk1, eval=chunk_name() %in% eval_chunks}
plot(cars)
```


```{r chunk2, eval=chunk_name() %in% eval_chunks}
plot(cars)
```

Thanks for any suggestions. Please let me know if my question is not clear.

like image 606
Bangyou Avatar asked Nov 18 '14 11:11

Bangyou


2 Answers

Knitr provided labels inside a chunk since 2012 (need more Google, https://github.com/yihui/knitr/issues/73).

This is my sample Rmd file:

---
output: html_document
---

```{r setup}
library(knitr)
eval_chunks <- c('chunk1', 'chunk3')
```

```{r chunk1, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```


```{r chunk2, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```


```{r chunk3, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
like image 146
Bangyou Avatar answered Sep 30 '22 18:09

Bangyou


I think this solution is imperfect because it requires a bit of care in making sure the correct chunks are evaluated, but it gets around the problem that chunk options are evaluated before hooks are called. In short, it doesn't use a hook, but instead uses the fact that chunk options can be R expressions. In this case, a function e() is used that relies on a global counter variable to dictate whether a particular chunk should be evaluated. Because chunks are evaluated in order, this works. In the below example, chunk1 and chunk3 are evaluated, but the others are not.

---
output: html_document
---

```{r setup}
library("knitr")
.i <- 2 # `setup` is the first chunk, so start at 2
.x <- all_labels() %in% c("chunk1", "chunk3")
e <- function(){
    d <- .x[.i]
    .i <<- .i + 1
    d
}
```

```{r chunk1, eval=e()}
x <- 1
x
```

```{r chunk2, eval=e()}
x <- 2
x
```

```{r chunk3, eval=e()}
x <- 3
x
```

```{r chunk4, eval=e()}
x <- 4
x
```
like image 31
Thomas Avatar answered Sep 30 '22 19:09

Thomas