使用knitr将降价文档的部分插入另一个降价文档中

Ric*_*bon 17 markdown r knitr r-markdown

我知道这可以用php和其他语言来完成,但是想知道是否可以使用knitr完成以下操作:

假设我有一个带有两个标题1部分的Rmarkdown(.rmd)文档:

# This is the first heading for the first document
Lorem ipsum dolor sit amet

# This is the second heading for the first document
plot(object)
Run Code Online (Sandbox Code Playgroud)
  1. 问题1:如果打开另一个.rmd文档,我该如何创建一个链接,以便在解析时,该文档将显示其内容以及第一个文档中的整个内容.例如:

    # This is the first heading for the second document
    Lorem ipsum dolor sit amet
    
    [command goes here to insert the first document]
    
    Run Code Online (Sandbox Code Playgroud)

    结果将是:

    # This is the first heading for the second document
    Lorem ipsum dolor sit amet
    
    # This is the first heading for the first document
    Lorem ipsum dolor sit amet
    
    # This is the second heading for the first document
    [plot shows up here]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 问题2:knitr允许我选择并仅将文档1的选定部分插入到文档2中吗?例如,仅标题1及其下方的内容,或仅标题2及其图

Yih*_*Xie 26

  1. 这就是块选项child的用途,例如second.Rmd,你可以

    ```{r child='first.Rmd'}
    ```
    
    Run Code Online (Sandbox Code Playgroud)
  2. 这有点棘手,但你可以knit_child()手动调用,例如

    ```{r echo=FALSE, results='asis'}
    # knit the first three lines of first.Rmd
    cat(knit_child(text = readLines('first.Rmd')[1:3]), sep = '\n')
    ```
    
    Run Code Online (Sandbox Code Playgroud)