Reputation: 210
I am writing a code inside a loop that looks like this:
for (i in c(1:5)) {
cat(" ", i,".","**", "Header one","**" , " " , sep = "\n")
cat("A)", "Subheader one" , sep = "\n")
cat("B)", "Subheader two" , sep = "\n")
}
I want it to appear in the rendered file as :
Header One
A) Subtitle one
B) Subtitle two
how to acheive that? Edit This is intended to be exported to word .docx
Upvotes: 0
Views: 1805
Reputation: 160687
A few thoughts:
Use the chunk option results="asis"
, this tells knitr
to write raw results from R into the output document (which assumes that it is valid in a markdown file) (ref: https://yihui.name/knitr/options/#text-results)
You don't actually have to force the increasing number for the top-level list, the numbers themselves are ignored by pandoc and converted into a sequential list (ref: https://pandoc.org/MANUAL.html#ordered-lists)
If you add too many spaces to the sublists, they may be considered a preformatted code block, so be careful. Namely, 8 is too many, 4 works.
This works:
---
output: html_document
---
```{r chunk1, echo=FALSE, results="asis"}
for (i in 1:5) {
cat("1. Header one",
" A) Subheader one",
" B) Subheader two",
sep = "\n")
}
```
produces this:
with this underlying HTML:
<ol style="list-style-type: decimal">
<li>Header one</li>
</ol>
<ol style="list-style-type: upper-alpha">
<li>Subheader one</li>
<li>Subheader two</li>
</ol>
<ol style="list-style-type: decimal">
<li>Header one</li>
</ol>
<ol style="list-style-type: upper-alpha">
<li>Subheader one</li>
<li>Subheader two</li>
...
Notes:
I find it confusing to have so many empty strings and such in your example, so I "efficiency'ed" them out. If you have specific formats you want/need, then you can do something like this with sprintf
:
---
output: html_document
---
```{r chunk1, echo=FALSE, results="asis"}
for (i in 1:5) {
cat(sprintf("1. Header %d", i),
sprintf(" A) Subheader one - %d", i),
" F) Subheader two",
sep = "\n")
}
```
to produce this:
c(1:5)
is the same as 1:5
, no c()
requirement
multiple calls to cat
are okay, realizing you need to closely manage the sep
s between parts of a single call and whatever is needed between calls to cat
(I prefer one call)
Edit
I exported this to Word, too, with:
---
output: word_document
---
and the sublevels are also indented correctly:
If you see something different, then this could be due to the style in place in the DOCX. This is typically controlled in the reference document, ref: https://rmarkdown.rstudio.com/word_document_format#style_reference. I'm using rmarkdown-1.10
on R-3.5.1, if that differs for you, consider your upgrade options.
Upvotes: 4