Programmatically insert text, headers and lists with R markdown

后端 未结 4 2154
时光说笑
时光说笑 2020-12-05 07:23

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

相关标签:
4条回答
  • 2020-12-05 07:43

    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.

    0 讨论(0)
  • 2020-12-05 07:45

    For people who want plots below each header, this is how I do it.

    ```{r, results="asis"}
    
    for (i in headers){
          cat("# ", i, "\n",
              knitr::knit_child("plot.Rmd", quiet = TRUE), "\n")
        }
    
    ```
    

    In the plot.Rmd put your plot code in it, e.g.

    ```{r}
    # plotting code
    ```
    
    0 讨论(0)
  • 2020-12-05 08:03

    This solution worked for me, compiling .Rmd to PDF in R 3.6.3:

    ```{r plot_loop_chunk, results='asis', tidy=FALSE}
    
    for(i in 1:10){
        cat("#", "Header", i, "\n")
    
        print(<some loop-dependent plot>)
    
        cat("\n")
        cat("\n")
    }
    
    ```
    
    0 讨论(0)
  • 2020-12-05 08:08

    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.

    0 讨论(0)
提交回复
热议问题