Rmarkdown's render() + knitr's spin(): How

2019-04-26 05:49发布

问题:

I'm generating html- and pdf-notebooks from R-scripts using rmarkdown's function render() and knitr's function spin(). Sometimes I use nested lists and mix them with code blocks. Here is an example using rmarkdown and knitr chunk options.

#' (1) This is normal text.
#'    (a) This is normal text but indented.
#+ echo = TRUE, eval = TRUE 
print("This is code")
#'    (b) This is supposed to be normal text with the same
#'        indentation as (a). However, it will be formatted as code.
#'        By this I mean that e.g. in a pdf-notebook it will be 
#'        correctly indented but the font will be the same font as 
#'        the code.

However, everything that follows the code after list item (a) will be marked up as code as well (e.g. (b)). But what I want to achieve is to have (b) marked up as normal text and use the same indentation as (a). Is it possible to do this?

回答1:

There is an internal chunk option indent that can add indentation to the chunk output. In your case, you can specify four spaces, e.g.

#+ echo = TRUE, eval = TRUE, indent = '    '


回答2:

You have to use what is called The four-space rule in the documentation: http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html#the-four-space-rule

So the following code works

  (1) This is normal text.

    Continued.

    (a) This is normal text but indented.

        ```{r, echo = TRUE, eval = TRUE} 
        summary(cars)
        ```

    (a) This is normal text with the same indentation as (a).

Note: There are

  • 2 Spaces infront of the (1)
  • 4 Spaces infront of each (a)
  • 8 Spaces infront of the code-block

Resulting in:

I ran it using rmarkdown::render("test.Rmd") and this is my session info

R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252    LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C                    LC_TIME=German_Germany.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
 [1] digest_0.6.8    evaluate_0.5.5  formatR_1.0     htmltools_0.2.6 knitr_1.9       rmarkdown_0.5.1
 [7] stringr_0.6.2   tools_3.1.1     XML_3.98-1.1    yaml_2.1.13