Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert portions of a markdown document inside another markdown document using knitr

I know this can be done with php and other languages, but was wondering whether the following could be accomplished using knitr:

Let's say I have an Rmarkdown (.rmd) document with two heading 1 sections:

# 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)
  1. Question 1: if open another .rmd document, how can i create a link so that when parsed this document would present its content as well as the whole content from the first document. For example:

    # This is the first heading for the second document
    Lorem ipsum dolor sit amet
    
    [command goes here to insert the first document]
    

    result would be:

    # 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]
    
  2. Question 2: would knitr allow me to select and insert only selected portions of document 1 into document 2? For example, only heading 1 and the content below it, or only heading 2 and its plot

like image 816
Ricardo Pietrobon Avatar asked Jul 11 '13 12:07

Ricardo Pietrobon


People also ask

What is the function of knitr in creating markdown document?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.

How can you compile the R Markdown document using knitr package?

The usual way to compile an R Markdown document is to click the Knit button as shown in Figure 2.1, and the corresponding keyboard shortcut is Ctrl + Shift + K ( Cmd + Shift + K on macOS). Under the hood, RStudio calls the function rmarkdown::render() to render the document in a new R session.

What are the three types of sections in an R Markdown document?

There are three basic components of an R Markdown document: the metadata, text, and code.


1 Answers

  1. that is what the chunk option child is for, e.g. in second.Rmd, you can

    ```{r child='first.Rmd'}
    ```
    
  2. that is a little bit trickier, but you can call knit_child() manually, e.g.

    ```{r echo=FALSE, results='asis'}
    # knit the first three lines of first.Rmd
    cat(knit_child(text = readLines('first.Rmd')[1:3]), sep = '\n')
    ```
    
like image 97
Yihui Xie Avatar answered Jan 03 '23 15:01

Yihui Xie