R built-in markdown

Im uses R Markdown in RStudio to create a report that mixes the output of Markdown and R. I know how to use the built-in R expressions in Markdown, but Im wonders how to do the opposite, i.e. use Markdown in R code. I want to loop calculations and get Markdown headers for each of them. I want headings for formatting (for example, in bold, etc.), and also be able to specify (sub) sections in the resulting PDF (which is a good feature of the way RMarkdown handles # and ##, etc.).

I know I can do the following:

--- title: "test" output: pdf_document --- #Section 1 ```{r, echo=FALSE} print(1+1) ``` #Section 2 ```{r, echo=FALSE} print(2+2) ``` #Section 3 ```{r, echo=FALSE} print(3+3) ``` 

Which gives something similar (approximately):

Section 1

## [1] 2

Section 2

## [1] 4

Section 3

## [1] 6

Is it possible to achieve the same result using something like that:

 --- title: "test2" output: pdf_document --- ```{r, echo=FALSE} for (i in 1:3) { print(paste("#Section",i)) print(i+i) } ``` 
+6
source share
2 answers

As @scoa pointed out, you should set the chunk results='asis' option. You should also place two \n both before and after your header.

 --- title: "test" output: pdf_document --- ```{r, echo=FALSE, results='asis'} for (i in 1:3) { cat(paste0("\n\n# Section", i, "\n\n")) print(i+i) cat("\n\n\\newpage") } ``` 
+3
source

As a more general answer, it would be useful to look at the markdownreports package, which parses the code (and output) from your R variables.

0
source

All Articles