5

I'm running into a duplicate label error when I call a function that uses knit inside a knit call. If I label the chunks the problem goes away. Is there a way to call some_function in a way that doesn't collide with the parent knit call?

library(knitr)
some_function <- function(){
    knit(text ="
    ```{r }
        1
    ```
    ")
}
cat(knit(text ="
```{r }
    some_function()   
```
```{r }
    some_function()   
```
"))

Output:

```r
some_function()
```

```
## Error: duplicate label 'unnamed-chunk-1'
```
Kalin
  • 1,691
  • 2
  • 16
  • 22
nachocab
  • 13,328
  • 21
  • 91
  • 149

2 Answers2

3

You can use knit_child() instead of knit() in some_function():

library(knitr)
some_function <- function(){
  knit_child(text ="
    ```{r }
        1
    ```
    ")
}
cat(knit(text ="
```{r }
    some_function()   
```
```{r }
    some_function()   
```
"))
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • Thanks a lot @Yihui ! If I understood the `knit` code correctly, setting the child mode ensures that no object gets written to the `.knitEnv`, which is what was messing me up. Correct? – nachocab Jul 12 '13 at 14:42
  • 1
    `knit()` will initialize some internal objects, including the object to manage code chunks, and `knit_child()` will not; if that object is initialized again, knitr will start counting chunks from 1 again, leading to the chunks with the same label `unnamed-chunk-1` in two nested `knit()` calls and they will clash – Yihui Xie Jul 12 '13 at 19:55
1

I don't understand exactly the context use of your code. Why not to use simply knitr child document feature?

Here a workaround ( hope that someone else come with a better solution specially you if you give more context)

some_function <- function(chunk.name='chunk1'){
  knit(text =sprintf("
    ```{r %s}
        1
    ```
    ",chunk.name))
}
cat(knit(text ="
```{r }
    some_function('a1')   
```
```{r }
    some_function('a2')   
```
"))
agstudy
  • 119,832
  • 17
  • 199
  • 261