When using R markdown if one wants to add text using code there are some simple ways to do it.
This is also true for tables, using the kable
command is very easy.
However, imagine you want to programmatically insert headers or lists to your report.
```{r, results='asis'} headers=list("We","are","your","friends") for (i in list_a){ #add i as header } ```
and you want this to be the same as writing in your Rmd file:
#We #are #your #friends
Another example would be to automatically create headers instead of lists:
```{r, results='asis'} list_a=list("We","are","your","friends") for (i in list_a){ #print i to a rmd list } ```
as before this should have the same result as writing:
*We *are *your *friends
This is not only a formatting problem as the table of context for Rmd files is created dynamically according to these headers.
We can insert headings and subheadings in R Markdown using the pound sign # . There are six heading/subheading sizes in R Markdown. The number of pound signs before your line of text determines the heading size, 1 being the largest heading and 6 being the smallest.
Rmd file, you may now add text to your document. You may start with the most basic word processing—simply typing your text below the YAML header section. If you want to start a new paragraph, you can simply hit Enter twice on your key- board, and begin writing again.
Upon installing, inserttable registers a new RStudio Addin (Insert Table) that can be used to easily insert a table in a Rmd document. To use it, open a Rmd or R document and select “Addins –> Insert Table”.
You need to construct your wanted markdown in R and use that together with the argument results = 'asis'
in your chunk options. Hence, something like the following will do what you want:
```{r, results='asis'} headers <- list("We","are","your","friends") for (i in headers){ cat("#", i, "\n") } ```
The for
-loop here will create the output
# We # are # your # friends
which is used directly as input in the .md document.
Use the pander package, which transform R objects into Pandoc's markdown:
> headers=list("We","are","your","friends") > list_a=list("We","are","your","friends") > library(pander) > pandoc.header(headers) # We # are # your # friends > pander(list_a) * We * are * your * friends <!-- end of list -->
The first example used a helper function to create the headers, while the second demo simply called the generic S3 method, that can robustly transform a variety of R objects into markdown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With