Automating the generation of preformated text in Rmarkdown using R

前端 未结 1 1079
情书的邮戳
情书的邮戳 2021-01-20 02:41

I\'m creating a document in which I repeat the same formatting multiple times. So I want to automate the process using the for loop in R. Here\'s a simple examp

相关标签:
1条回答
  • 2021-01-20 03:11

    For this kind of task, you can use glue package to evaluate R expressions inside character strings.

    Here's an Rmd file that answer your question:

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r echo=FALSE, results='asis'}
    library(data.table) 
    
    dt <- data.table(ggplot2::diamonds)
    for (cutX in unique(dt$cut)) {
      dtCutX <- dt[cut==cutX, lapply(.SD,mean), .SDcols=5:7]
      cat("\n\n# Section: The Properties of Cut `cutX`\n")  
      cat(glue::glue("This Section describes the properties of cut {cutX}. Table below shows its mean values:\n"))
      print(knitr::kable(dtCutX))
      cat(glue::glue("\n\nThe largest carat value for cut {cutX} is {dt[cut=='Ideal', max(carat)]}\n"))
    }
    ```
    
    0 讨论(0)
提交回复
热议问题