【问题标题】:knit_child in a loop - variable as title循环中的 knit_child - 变量作为标题
【发布时间】:2017-10-07 23:21:07
【问题描述】:

thisthis stackoverflow-questions 之后,我尝试在循环中使用 knit-child,其中包含一个变量定义的标题。

我得到的不是变量(例如 A、B、C)作为标题,而是带有 # 仍然附加(# A、#B、#C)

家长:

---
title: "Untitled"
output: html_document
---

```{r,include=FALSE}
library(knitr)
```


```{r,echo=FALSE}

titles<-LETTERS[1:3]

```

```{r,include=FALSE,echo=FALSE}
out = NULL
for (i in titles){
  out = c(out, knit_child('Child.Rmd'))
}
```


`r paste(out, collapse='\n')`

孩子:

---
title: "Untitled"

output: html_document
---


```{r,echo=FALSE,results='asis'}

cat("\n\n # ", i,"\n")

```

```{r,echo=FALSE,results='asis'}

cat("\n\n This text is about ", i,"\n")

```

输出:

虽然我更喜欢:

【问题讨论】:

  • 没时间检查这个,但请尝试将cat("\n\n # ", i,"\n") 替换为cat("\n\n# ", i,"\n")(哈希前没有空格)。
  • @CL。你是对的。如果您将其粘贴到答案中,我会接受它

标签: r knitr r-markdown


【解决方案1】:

# 字符仅表示 Markdown 中的标题,如果它是该行的第一个字符。

cat("\n\n # ", i,"\n") 产生两个新行,然后是一个空格,然后#。删除空格以解决问题:

cat("\n\n# ", i,"\n")

【讨论】:

    【解决方案2】:

    考虑使用pandoc.header而不是Cat

    i = 1
    pander::pandoc.header(i, level = 1)
    > # 1
    
    pander::pandoc.header(paste0("Subheading ", i), level = 3)
    > ### Subheading 1
    

    【讨论】:

      【解决方案3】:

      我推荐使用knit_expand 函数。

      您将 Child.Rmd 创建为

      # {{current_title}}
      
      This text is about {{current_title}}
      
      Remember that `current_title` is a literal string, so
      if you want use it in code then must be quoted:
      
      <!-- Use `current_title` in chunk name to avoid duplicated labels -->
      
      ```{r {{current_title}}} 
      data.frame({{current_title}} = "{{current_title}}")
      ```
      

      那么你的主文档应该是这样的:

      ---
      title: "Untitled"
      output: html_document
      ---
      
      ```{r,include=FALSE}
      library(knitr)
      ```
      
      
      ```{r,echo=FALSE}
      
      titles<-LETTERS[1:3]
      
      ```
      
      ```{r,include=FALSE,echo=FALSE}
      expanded_child <- lapply(
          titles
          ,function(xx) knit_expand("Child.Rmd", current_title = xx)
          )
      
      parsed_child <- knit_child(text = unlist(expanded_child))
      
      ```
      
      `r parsed_child`
      

      结果:

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 2015-03-30
        • 1970-01-01
        • 2017-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多