How to nest knit calls to fix duplicate chunk label errors?

自古美人都是妖i 提交于 2019-12-30 10:35:39

问题


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

回答1:


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()   
```
"))



回答2:


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


来源:https://stackoverflow.com/questions/17535227/how-to-nest-knit-calls-to-fix-duplicate-chunk-label-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!