Jump to content

Rmarkdown: Difference between revisions

From 太極
Brb (talk | contribs)
Brb (talk | contribs)
 
(122 intermediate revisions by the same user not shown)
Line 18: Line 18:
* [https://github.com/dgrapov/TeachingDemos/blob/master/Demos/OPLS/OPLS%20example.md Example from hosted in github]
* [https://github.com/dgrapov/TeachingDemos/blob/master/Demos/OPLS/OPLS%20example.md Example from hosted in github]
* [https://www.makeuseof.com/why-is-markdown-popular-reasons-you-should-use-it/ Why Is Markdown So Popular? 7 Reasons You Should Use It]
* [https://www.makeuseof.com/why-is-markdown-popular-reasons-you-should-use-it/ Why Is Markdown So Popular? 7 Reasons You Should Use It]
== Editors ==
[https://www.howtogeek.com/why-you-should-be-writing-everything-in-markdown/ Why You Should Be Writing Everything in Markdown] 2023/10/11.


== Github markdown Readme.md ==
== Github markdown Readme.md ==
Line 46: Line 49:
| You Can Also  | Put Pipes In | Like this \| |
| You Can Also  | Put Pipes In | Like this \| |
</pre>
</pre>
== Include code ==
[https://markdown.land/markdown-code-block Markdown Code Block: Including Code In .md Files]
<ul>
<li>Inline code blocks:
<pre>
Use `print("Hello, world!")` to print a message to the screen.
</pre>
<li>Fenced code blocks:
<pre>
```python
print("Hello, world!")
for i in range(10):
    print(i)
```
</pre>
<li>Indented code blocks
<pre>
Here's some regular text. And now a code block:
    print("Hello, world!")
    if True:
        print('true!')
</pre>
</ul>


== Literate programming ==
== Literate programming ==
Line 60: Line 88:
* https://www.rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf
* https://www.rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf
* Chunk options http://kbroman.org/knitr_knutshell/pages/Rmarkdown.html
* Chunk options http://kbroman.org/knitr_knutshell/pages/Rmarkdown.html
* [https://itsfoss.com/r-markdown/ Beginner's Guide to R Markdown Syntax (With Cheat Sheet)]


HTML5 slides examples
HTML5 slides examples
Line 97: Line 126:


== Tips ==  
== Tips ==  
[https://indrajeetpatil.github.io/RmarkdownTips/ RMarkdown Tips and Tricks]
* [https://www.rstudio.com/blog/r-markdown-tips-tricks-4-looks-better-works-better/ R Markdown Lesser-Known Tips & Tricks #4: Looks Better, Works Better]
* [https://www.rstudio.com/blog/r-markdown-tips-and-tricks-3-time-savers/ R Markdown Tips and Tricks #3: Time-savers & Trouble-shooters]
*# Convert an R script into an R markdown document with knitr::spin()
*# Convert an R markdown document into an R script with knitr::purl()
*# Reuse code chunks throughout your document
*# Cache your chunks (with dependencies)
*# Save the content of a chunk elsewhere with the cat engine
*# Include parameters to easily change values
*# Create templates with knit_expand()
*# Exit knitting early with knit_exit()
* [https://www.rstudio.com/blog/r-markdown-tips-tricks-2-cleaning-up-your-code/ R Markdown Lesser-Known Tips & Tricks #2: Cleaning Up Your Code]
* [https://www.rstudio.com/blog/r-markdown-tips-tricks-1-rstudio-ide/ R Markdown Lesser-Known Tips & Tricks #1: Working in the RStudio IDE]
* [https://indrajeetpatil.github.io/RmarkdownTips/ RMarkdown Tips and Tricks]
* [https://raukr-2022-rmd-skills.netlify.app/ Improve your R Markdown Skills] 2022/6/13
* [https://www.r-bloggers.com/2023/04/11-tricks-to-level-up-your-rmarkdown-documents/ 11 tricks to level up your rmarkdown documents] 2023/4/15
* [https://readmedium.com/optimizing-rmarkdown-documents-tips-for-efficient-reporting-e8653116d5d9 Optimizing RMarkdown Documents: Tips for Efficient Reporting] 11/17/2023, [https://addons.mozilla.org/en-US/firefox/addon/medium-parser/ Medium parser] by Xatta Trone
 
=== Debug ===
[https://adv-r.hadley.nz/debugging.html#rmarkdown Debugging RMarkdown]
 
== YAML ==
== YAML ==
[https://github.com/r-lib/ymlthis ymlthis] package - write YAML for R Markdown, bookdown, blogdown, and more.
* [https://github.com/r-lib/ymlthis ymlthis] package - write YAML for R Markdown, bookdown, blogdown, and more.
* '''R Markdown Crash Course''' [https://zsmith27.github.io/rmarkdown_crash-course/lesson-4-yaml-headers.html YAML Headers]


Some examples
Some examples
Line 133: Line 182:
=== HTML output ===
=== HTML output ===
[https://scienceloft.com/technical/useful-yaml-options-for-generating-html-reports-in-r/ Useful YAML options for generating HTML reports in R]
[https://scienceloft.com/technical/useful-yaml-options-for-generating-html-reports-in-r/ Useful YAML options for generating HTML reports in R]
=== HTML Turn off title ===
[https://stackoverflow.com/a/59679986 Rmarkdown: Turn off title]
=== HTML with dynamic table of contents ===
* https://juba.github.io/rmdformats/
* https://bookdown.org/yihui/rmarkdown/rmdformats.html. We need to install the package "rmdformats" first.
<pre>
---
title: "My title"
output:
  rmdformats::robobook:
    highlight: tango
    number_sections: true
    lightbox: true
    gallery: true
    code_folding: hide
---
</pre>


=== Inlcude latex packages ===
=== Inlcude latex packages ===
Line 153: Line 221:
---
---
title: "Homework"
title: "Homework"
output: word_document
output:
  html_document:
    code_folding: hide
    toc: true
    toc_float: true
    theme: "flatly"
params:
params:
   run: TRUE
   run: TRUE
---
---


```{r chunk1, eval = params$run}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = params$run)
```
 
```{r chunk1}
dim(iris)
dim(iris)
```
```
</pre>
We can use the following command to create an html file that does not evaluate the code for the whole document.
<pre>
rmarkdown::render("Homework.Rmd",
          params=list(run = FALSE),
          output_file = "Homework.html")
</pre>
</pre>


Line 185: Line 268:


=== Office (Word, Powerpoint) output ===
=== Office (Word, Powerpoint) output ===
[https://davidgohel.github.io/officer/ officer] R package
<ul>
<li>[https://davidgohel.github.io/officer/ officer] R package
<pre>
# Load the officer and flextable packages
library(officer)
library(flextable)
 
# Create a new Word document
doc <- read_docx()
 
# Create some data
data <- iris[1:5, ]
 
# Add a title to the document
doc <- body_add_par(doc, "My Table", style = "heading 1")
 
# Create a table using the flextable() function
my_table <- flextable(data)
 
# Add the table to the Word document
doc <- body_add_flextable(doc, my_table)
 
# Write the Word document to a file
print(doc, target = "my_word_document.docx")
</pre>
<li>Landscape:
* [https://rmarkdown.rstudio.com/articles_docx.html Happy collaboration with Rmd to docx] and [https://stackoverflow.com/a/52722548 Unable to produce landscape orientation]. Works for me.
* [https://davidgohel.github.io/officedown/ officedown] package, [https://stackoverflow.com/a/73769125 R markdown landscape-only word document], [https://bookdown.org/yihui/rmarkdown-cookbook/word-officedown.html 8.3 Style individual elements]. The package was suggested by [https://cloud.r-project.org/web/packages/flextable/index.html flextable]. Not working for me.
 
<li>Use a customized word template. [https://fortune9.netlify.app/2024/01/28/rmarkdown-automate-word-document-generation-using-rmarkdown/ Automate word document generation using Rmarkdown]
</ul>
 
=== Examples ===
[https://github.com/tenglongli/ComBatCorr/tree/master/Example ComBatCorr], [https://htmlpreview.github.io/?https://github.com/tenglongli/ComBatCorr/blob/master/Example/Manuscript-Output.html Preview HTML]
<pre>
---
title: "..."
author: "..."
output:
  html_document:
    code_folding: hide
    toc: true
    toc_float: true
    theme: "flatly"
editor_options:
  chunk_output_type: console
---
</pre>
PDF output
<pre>
---
title: "..."
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  pdf_document:
    toc: true
    toc_depth: 3
    number_sections: true
    fig_caption: true
urlcolor: blue
---
</pre>


== Chunk options ==
== Chunk options ==
Line 200: Line 344:
* include. whether to include the chunk output in the final output document;
* include. whether to include the chunk output in the final output document;
* '''warning'''. whether to preserve warnings (produced by warning()) in the output like we run R code in a terminal (<strike>if FALSE, all warnings will be printed in the console instead of the output document</strike>). ''This seems to be useful''. Too many warnings will make the computation time much longer (eg. 3 hours vs 30 minutes) no to say the output file will be very large.
* '''warning'''. whether to preserve warnings (produced by warning()) in the output like we run R code in a terminal (<strike>if FALSE, all warnings will be printed in the console instead of the output document</strike>). ''This seems to be useful''. Too many warnings will make the computation time much longer (eg. 3 hours vs 30 minutes) no to say the output file will be very large.
* error. whether to preserve errors (from stop()); by default, the evaluation will not stop even in case of errors!! if we want R to stop on errors, we need to set this option to FALSE
* error. whether to preserve errors (from stop()); If you want to show the errors without stopping R, you may use the chunk option error = TRUE. See [https://bookdown.org/yihui/rmarkdown-cookbook/opts-error.html Do not stop on error]
* comment. [https://stackoverflow.com/a/15081230 Remove Hashes in R Output from R Markdown and Knitr]
* comment. [https://stackoverflow.com/a/15081230 Remove Hashes in R Output from R Markdown and Knitr]
<pre>
<pre>
Line 210: Line 354:


=== Global options ===
=== Global options ===
Suppose I want to create a simple markdown only documentation without worrying about executing code, instead of adding eval = FALSE to each code chunks, I can insert the following between YAML header and the content. Even bash chunks will not be executed.
<ul>
<li>Suppose I want to create a simple markdown only documentation without worrying about executing code, instead of adding eval = FALSE to each code chunks, I can insert the following between YAML header and the content. Even bash chunks will not be executed.
<pre>
<pre>
```{r setup, include=FALSE}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = FALSE)
knitr::opts_chunk$set(echo = TRUE, eval = FALSE)
```
</pre>
<li>When you knit an R Markdown document, knitr by default sets the working directory to the location of the .Rmd file, not the project root. With the following line, it makes knitr behave as if the R Markdown file is always executed from the project root, even if the .Rmd is in a subfolder. [https://bookdown.org/yihui/rmarkdown-cookbook/working-directory.html The working directory for R code chunks] from '''R Markdown Cookbook'''.
<pre>
```{r setup, include=FALSE}
knitr::opts_knit$set(root.dir = here::here())
```
```
</pre>
</pre>
=== Include sections inside a chunk ===
<pre>
```{r}
# Chunk section 1 ----
...
# Chunk section 2 ----
```
</pre>
=== Ignore duplicate chunk labels ===
I got an error '''Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block Execution halted''' because of duplicate chunk labels.
See [https://bookdown.org/yihui/rmarkdown-cookbook/duplicate-label.html Chapter 14 Miscellaneous knitr Tricks]


=== Include all the code from the Rmd ===
=== Include all the code from the Rmd ===
Line 252: Line 417:
=== Conditional evaluation using params ===
=== Conditional evaluation using params ===
See [[#render.28.2C_params.29|here]]
See [[#render.28.2C_params.29|here]]
=== Conditional code for specific output formats ===
Breaking the page in LaTeX output for PDFs. Note that commands passed to LaTeX in this way need to be escaped with a double slash.
<pre>
`r if (knitr::is_latex_output()) '\\newpage'`
</pre>


=== results = "asis" ===
=== results = "asis" ===
[https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html Output text as raw Markdown content]
[https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html Output text as raw Markdown content]
== "source" (run) all of the code chunks in a .qmd file ==
[https://twitter.com/rlbarter/status/1646249384403959808?s=20 "source" (run) all of the code chunks in a .qmd file (like `source("analysis.qmd")`) inside another .qmd file?] See [https://bookdown.org/yihui/rmarkdown-cookbook/purl.html 3.4 Convert R Markdown to R script]
<pre>
```{r}
library(knitr)
temp_r_file <- tempfile(fileext = '.R')
purl("first-file.qmd", output = temp_r_file)
source(temp_r_file)
unlink(temp_r_file)
```
</pre>


== Multiple plots/tables in one chunk ==
== Multiple plots/tables in one chunk ==
[https://twitter.com/dgkeyes/status/1479208406799978496 twitter]
[https://twitter.com/dgkeyes/status/1479208406799978496 twitter]
== Reuse code chunks, combine chunks ==
See [https://www.rstudio.com/blog/r-markdown-tips-and-tricks-3-time-savers/ R Markdown Tips and Tricks #3: Time-savers & Trouble-shooters]


== Comment chunks not working ==
== Comment chunks not working ==
Line 263: Line 449:


== inline code ==
== inline code ==
https://rmarkdown.rstudio.com/lesson-4.html
https://rmarkdown.rstudio.com/lesson-4.html ('''`r x<-5 `''')


== Language support (engine) ==
== Language support (engine) ==
Line 344: Line 530:


== Knit button ==
== Knit button ==
* It calls rmarkdown::render()
* It calls '''rmarkdown::render()'''
* It does not count as an interactive session. But if we call '''rmarkdown::render()''' in an R session, it counts as an interactive session.
* R Markdown = knitr + Pandoc
* R Markdown = knitr + Pandoc
* rmarkdown::render () = knitr::knit() + a system() call to pandoc
* rmarkdown::render() = knitr::knit() + a system() call to pandoc


=== Exit knitting early ===
=== Exit knitting early ===
Line 352: Line 539:


== Pandoc's Markdown ==
== Pandoc's Markdown ==
'''pandoc''' will be installed automatically if we install '''tidyverse''' by using '''sudo apt install r-cran-tidyverse''' binary package.
Originally Pandoc is for html.
Originally Pandoc is for html.


Line 403: Line 592:


* [https://github.com/rstudio/rticles rticles] package
* [https://github.com/rstudio/rticles rticles] package
* [https://github.com/juba/rmdformats rmdformats] package
* [https://github.com/juba/rmdformats rmdformats] package. For each format, it also takes the option from [https://bookdown.org/yihui/rmarkdown/html-document.html html_document] such as '''code_folding''' (the default is 'none' so there is no way to control it on HTML).
** downcute: how to turn off black color
** '''robobook''': looks pretty. TOC is on LHS & can be closed like bookdown theme.
** material
** readthedown
** html_clean: the TOC is kind of small
** html_docco
<pre>
output:
  rmdformats::robobook:
    highlight: tango
    number_sections: true
    lightbox: true
    gallery: true
    code_folding: show
</pre>


== rmarkdown news, floating TOC ==
== rmarkdown news, floating TOC ==
Line 489: Line 693:
include_graphics(img1_path)  
include_graphics(img1_path)  
```
```
</pre>
5. [https://bookdown.org/yihui/rmarkdown-cookbook/figure-size.html Control the size of plots/images]. It works.
<pre>
![A nice image.](foo/bar.png){width=50%}
</pre>
</pre>


Line 502: Line 711:
! Comment
! Comment
|-
|-
| kable
| knitr
|  
| kable()
|
|
|-
|-
Line 521: Line 730:
* [https://www.rstudio.com/blog/winners-of-the-2021-table-contest/ Winners of the 2021 Table Contest],  
* [https://www.rstudio.com/blog/winners-of-the-2021-table-contest/ Winners of the 2021 Table Contest],  
** [https://rpubs.com/JackDavison/gt-openair Using {gt} and {openair} to Present Air Quality Data] can integrate clickable figures in tables. In order to reproduce the expandable figures as seen on the html, we need to download the gt.svg and Rmd file (table-contest-rmd.Rmd) and rebuild the html file.  The expandable figures/gallery feature relies on the [https://juba.github.io/rmdformats rmdformats] package (gallery: TRUE) and the [https://dimsemenov.com/plugins/magnific-popup/ lightbox] effect.
** [https://rpubs.com/JackDavison/gt-openair Using {gt} and {openair} to Present Air Quality Data] can integrate clickable figures in tables. In order to reproduce the expandable figures as seen on the html, we need to download the gt.svg and Rmd file (table-contest-rmd.Rmd) and rebuild the html file.  The expandable figures/gallery feature relies on the [https://juba.github.io/rmdformats rmdformats] package (gallery: TRUE) and the [https://dimsemenov.com/plugins/magnific-popup/ lightbox] effect.
* [https://www.rstudio.com/blog/rstudio-community-table-gallery/ RStudio Community Table Gallery]


=== kable ===
=== knitr::kable ===
[https://rpahl.github.io/r-some-blog/quicker-knitr-kables-in-rstudio-notebook/ Quicker knitr kables in RStudio notebook]
* https://bookdown.org/yihui/rmarkdown-cookbook/kable.html
* [https://www.r-bloggers.com/2019/11/quicker-knitr-kables-in-rstudio-notebook/ Quicker knitr kables in RStudio notebook]
 
=== From scratch ===
[https://tomaztsql.wordpress.com/2023/03/26/little-useless-useful-r-functions-transforming-dataframe-to-markdown-table/ Little useless-useful R functions – Transforming dataframe to markdown table]


=== Caption and special character ===
=== Caption and special character ===
Line 542: Line 756:
   kable_styling(font_size = 8, latex_options = c("striped", "hold_position"))
   kable_styling(font_size = 8, latex_options = c("striped", "hold_position"))
</pre>
</pre>
[https://stackoverflow.com/a/44555902 Alternate row color with knitr:kable in R Markdown]
<pre>
knitr::kable(mtcars, "html") %>%
  kable_styling("striped")
</pre>
[https://stackoverflow.com/a/48512819 kable kableExtra, Cells with hyperlinks]


[https://stackoverflow.com/a/44888475 How to stop bookdown tables from floating to bottom of the page in pdf?]
[https://stackoverflow.com/a/44888475 How to stop bookdown tables from floating to bottom of the page in pdf?]
Line 554: Line 774:
* [https://stackoverflow.com/a/64129080 R gt_table adjust row height]
* [https://stackoverflow.com/a/64129080 R gt_table adjust row height]
* [https://datavizpyr.com/how-to-make-beautiful-tables-with-gtextras/ How to Make Beautiful Tables with gtExtras]
* [https://datavizpyr.com/how-to-make-beautiful-tables-with-gtextras/ How to Make Beautiful Tables with gtExtras]
* [https://themockup.blog/posts/2022-06-13-gtextras-cran/ Beautiful tables in R with gtExtras] 2022-06-13
* [https://www.rstudio.com/blog/all-new-things-in-gt-0-7-0/ All the New Things in {gt} 0.7.0]


Include images in tables
Include images in tables
Line 644: Line 866:


=== tableone ===
=== tableone ===
https://cran.r-project.org/web/packages/tableone/
<ul>
<li>https://cran.r-project.org/web/packages/tableone/
<li>[https://www.r-bloggers.com/2016/02/table-1-and-the-characteristics-of-study-population/ Table 1 and the Characteristics of Study Population]
* The demo data can be downloaded
* [https://www.rdocumentation.org/packages/tableone/versions/0.13.2/topics/CreateTableOne ?CreateTableOne]
* It can be verified that if the interested variable is continuous, we can use '''t.test'''(, var.equal = T)$p.value to obtain p-values. Or use the '''aov''' function: <nowiki>summary(aov(BMI ~ Gender, dt))[[1]][["Pr(>F)"]][1] </nowiki> .
* If the interested variable is discrete, it seems it uses '''chi.square'''(var1, var2)$p.value to obtained p-values. It seems even the cells have small number of observations, it still use chisq-test. We can however obtain the Fisher's exact test p-values in the print() method.
<pre>
R> with(dt[1:15,], table(Smoking, Gender))
      Gender
Smoking Female Male
    No      5    6
    Yes      2    2
 
R> with(dt[1:15,], chisq.test(table(Education, Gender))$p.value)
[1] 0.6691241
Warning message:
In chisq.test(table(Education, Gender)) :
  Chi-squared approximation may be incorrect
R> with(dt[1:15,], fisher.test(table(Education, Gender))$p.value)
[1] 0.8135198
 
R> CreateTableOne(c("Smoking", "Education"), dt[1:15,], catVars, strata = c("Gender"))
                  Stratified by Gender
                    Female    Male      p      test
  n                7        8                   
  Smoking = Yes (%) 2 (28.6)  2 (25.0)  1.000   
  Education (%)                          0.669   
    High          2 (28.6)  4 (50.0)           
    Low            3 (42.9)  2 (25.0)           
    Medium        2 (28.6)  2 (25.0) 
 
R> print(CreateTableOne(c("Smoking", "Education"), dt[1:15,], catVars, strata = c("Gender")),
        exact = c("Smoking", "Education"))
                  Stratified by Gender
                    Female    Male      p      test
  n                7        8                   
  Smoking = Yes (%) 2 (28.6)  2 (25.0)  1.000 exact
  Education (%)                          0.814 exact
    High          2 (28.6)  4 (50.0)             
    Low            3 (42.9)  2 (25.0)             
    Medium        2 (28.6)  2 (25.0) 
 
# The print() result is a table so we can output it using write.table()
R> print(CreateTableOne(c("Smoking", "Education"), dt[1:15,], catVars, strata = c("Gender")),
        exact = c("Smoking", "Education")) %>% dim()
# [1] 6 4
</pre>
<li>[https://www.jianshu.com/p/40b7db26e7e6 简书]
</ul>


=== printr ===
=== printr ===
Line 653: Line 924:


=== flextable ===
=== flextable ===
[https://cran.r-project.org/web/packages/flextable/index.html flextable]. Create pretty tables for 'HTML', 'Microsoft Word' and 'Microsoft PowerPoint' documents.
<ul>
<li>[https://cran.r-project.org/web/packages/flextable/index.html flextable]. Create pretty tables for 'HTML', 'Microsoft Word' and 'Microsoft PowerPoint' documents.
<syntaxhighlight lang='r'>
library(flextable)
df <- data.frame(a=letters[1:3], b=rnorm(3), c=letters[4:6])
df <- flextable(df)
df <- add_header_row(ft, c("Merge Header", "Header 3"))
df <- align(ft, align = 'center', part = 'header')
df <- align(ft, j=1:3, align='center', part='body')
df <- set_caption(ft, caption = 'my table caption')
df <- add_footer_lines(df, values = c("blah 1", "blah 2"))
# Output to Word
library(officer)
doc <- read_docx()
doc <- body_add_flextable(doc, ft)
print(doc, target = "output.docx")
</syntaxhighlight>
<li>[https://ardata-fr.github.io/flextable-book/index.html ebook] with [https://ardata-fr.github.io/flextable-book/static/pdf/cheat_sheet_flextable.pdf cheat sheet]. Search "library" to find examples, especially the chapter [https://ardata-fr.github.io/flextable-book/as-flextable.html Chapter 9 Transform objects into flextable]
<pre>
---
title: "Untitled2"
output:
  word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```


[https://ardata-fr.github.io/flextable-book/assets/pdf/cheat_sheet_flextable.pdf Cheat sheet]
```{r echo=FALSE}
ft <- flextable(head(mtcars))
ft <- autofit(ft)
ft
```
 
A new chunk
```{r results='asis', echo = FALSE}
ft <- set_caption(ft, caption = "Table 1: New York Air Quality Measurements")
theme_zebra(ft) # ft <- theme_zebra(ft)
```
</pre>
</ul>


=== sparkTable ===
=== sparkTable ===
Line 666: Line 976:
=== mmtable2 ===
=== mmtable2 ===
[https://github.com/ianmoran11/mmtable2?s=09 mmtable2] allows you to create and combine tables with a ggplot2/patchwork syntax.
[https://github.com/ianmoran11/mmtable2?s=09 mmtable2] allows you to create and combine tables with a ggplot2/patchwork syntax.
=== tinytable ===
https://vincentarelbundock.github.io/tinytable/


== How to align table and plot in rmarkdown html_document ==
== How to align table and plot in rmarkdown html_document ==
https://stackoverflow.com/a/54359010
https://stackoverflow.com/a/54359010


== Equations ==
== Math equations ==
[https://github.com/datalorax/equatiomatic equationmatic] package
* [https://rpruim.github.io/s341/S19/from-class/MathinRmd.html Mathematics in R Markdown] R Pruim
* [https://rmd4sci.njtierney.com/math RMarkdown for Scientists]
* [https://github.com/datalorax/equatiomatic equationmatic] package


== RMarkdown Template that Manages Academic Affiliations ==
== RMarkdown Template that Manages Academic Affiliations ==
Line 716: Line 1,031:
* [https://docs.google.com/presentation/d/1qFUgYpHDmy68-oaaWS196zrsACtiyj2C65GZAjDDyNs/ Rmd Workflows Make New Statistical Methods Accessible to Biomedical Researchers] Michael Love 2020
* [https://docs.google.com/presentation/d/1qFUgYpHDmy68-oaaWS196zrsACtiyj2C65GZAjDDyNs/ Rmd Workflows Make New Statistical Methods Accessible to Biomedical Researchers] Michael Love 2020
* [https://bioconductor.org/packages/release/bioc/html/easyreporting.html easyreporting] package. [https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0244122 Easyreporting simplifies the implementation of Reproducible Research layers in R software] (paper)
* [https://bioconductor.org/packages/release/bioc/html/easyreporting.html easyreporting] package. [https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0244122 Easyreporting simplifies the implementation of Reproducible Research layers in R software] (paper)
* [https://cran.r-project.org/web/packages/reprex/index.html reprex]: Prepare Reproducible Example Code via the Clipboard


== html document ==
== html document ==
Line 752: Line 1,068:
* [https://www.garrickadenbuie.com/blog/r-colors-css/?s=09 R Colors in CSS for R Markdown HTML Documents]
* [https://www.garrickadenbuie.com/blog/r-colors-css/?s=09 R Colors in CSS for R Markdown HTML Documents]
* [https://emilyriederer.netlify.app/post/snow/ How to Make R Markdown Snow]
* [https://emilyriederer.netlify.app/post/snow/ How to Make R Markdown Snow]
=== Scrollable code/output ===
* [https://bookdown.org/yihui/rmarkdown-cookbook/html-scroll.html 7.4 Scrollable code blocks],
** [https://github.com/rstudio/rmarkdown-cookbook/issues/75 Scrollable code output #75] 2018
** [https://stackoverflow.com/a/67942965 Vertically scrollable code with RStudio and xaringan]
** [https://stackoverflow.com/questions/50919104/horizontally-scrollable-output-on-xaringan-slides Horizontally scrollable output on xaringan slides]
=== Download button/embed files ===
* [https://cran.r-project.org/web/packages/downloadthis/index.html downloadthis]: Implement Download Buttons in 'rmarkdown'
* [https://bookdown.org/yihui/rmarkdown-cookbook/html-css.html 7.1 Apply custom CSS]
<pre>
```{css echo = F}
.button_green {
  background-color: #4CAF50;
  font-size: 14px;
}
```
```{r}
library(downloadthis)
# Use the class parameter in download_this to apply your custom class
mtcars %>% download_this(
  output_name = "mtcars",
  output_extension = ".xlsx",
  button_label = "Download datasets as xlsx",
  button_type = "warning", 
  has_icon = TRUE,
  icon = "fa fa-save",
  class = "button_green" # Add your custom class here
)
```
</pre>
<syntaxhighlight lang='r'>
library(download_this)
# Custom CSS for the button
button_css <- "
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  border-radius: 4px;
"
# Create the download button
download_this(mtcars, style = button_css,
              str_anvlopt = "Download Data",
              output_name = "my_data.csv")
</syntaxhighlight>


== Dropdown menu ==
== Dropdown menu ==
[http://walkerke.github.io/2016/12/rmd-dropdowns/ Dropdown menus in R Markdown with bsselectR]
<ul>
<li>plotly package. [https://plotly.com/r/dropdowns/  Dropdown Events in R]
* [https://statisticsglobe.com/dropdown-menu-plotly-graph-r Create Dropdown Menu in plotly Graph in R (Example)]
* [https://sylwiamielnicka.com/blog/advanced-plotly-sliders-and-dropdown-menus/ Advanced Plotly – Sliders and dropdown menus]
<li>[http://walkerke.github.io/2016/12/rmd-dropdowns/ Dropdown menus in R Markdown with bsselectR]
<pre>
<pre>
devtools::install_github("walkerke/bsselectR")
devtools::install_github("walkerke/bsselectR")
Line 763: Line 1,140:
bsselect(state_plots, type = "img")
bsselect(state_plots, type = "img")
</pre>
</pre>
</ul>


== Automatic document production with R ==
== Automatic document production with R ==
Line 778: Line 1,156:
* https://bookdown.org/yihui/rmarkdown/presentations.html
* https://bookdown.org/yihui/rmarkdown/presentations.html
* https://codingclubuc3m.rbind.io/post/2019-09-24/
* https://codingclubuc3m.rbind.io/post/2019-09-24/
=== 4 output format ===
* HTML (ioslides) you can print ioslides to PDF with Chrome. [https://bookdown.org/yihui/rmarkdown/ioslides-presentation.html 4.1 ioslides presentation], [https://garrettgman.github.io/rmarkdown/ioslides_presentation_format.html Presentations with ioslides Overview]
* HTML (Slidy) you can print ioslides to PDF with Chrome
* PDF (beamer) requires TeX
* PowerPoint
=== font size ===
* [https://bookdown.org/yihui/rmarkdown/slidy-presentation.html Slidy presentation]
* [https://github.com/rstudio/rmarkdown-book/issues/30 Adjusting font-size in ioslides using R Markdown]
=== Presenter mode ===
* [https://bookdown.org/yihui/rmarkdown/ioslides-presentation.html#presenter-mode ioslides presentation]
*# Follow [https://bookdown.org/yihui/rmarkdown/ioslides-presentation.html#presenter-mode this] to add notes to your Rmd file.
*# Add "?presentme=true" to the end of the URL of HTML file in your browser. This will popup another window/tab and this is the presenter will control and see all the notes. The original window/tab will be used by viewers. On my Chrome browser, I need to allow a popup from this location. Firefox is easy to allow popup. [https://support.apple.com/guide/safari/block-pop-ups-sfri40696/mac Safari browser] is difficult.
*# Use the "p" key to change the mode to [https://bookdown.org/yihui/rmarkdown/ioslides-presentation.html#display-modes Presenter mode]. You will see the notes at the bottom of the screen. If the notes are very long, a slider will be shown on the RHS.
* [https://bookdown.org/yihui/rmarkdown/xaringan-format.html#xaringan-notes xaringan Presentations]
** [https://bookdown.org/yihui/rmarkdown/xaringan-format.html#xaringan-notes Presenter notes]


=== PowerPoint slides ===
=== PowerPoint slides ===
Line 783: Line 1,179:
* https://bookdown.org/yihui/rmarkdown/powerpoint-presentation.html
* https://bookdown.org/yihui/rmarkdown/powerpoint-presentation.html
* [https://support.rstudio.com/hc/en-us/articles/360004672913-Rendering-PowerPoint-presentations-with-RStudio#templates Rendering PowerPoint Presentations with RStudio]
* [https://support.rstudio.com/hc/en-us/articles/360004672913-Rendering-PowerPoint-presentations-with-RStudio#templates Rendering PowerPoint Presentations with RStudio]
* [https://appsilon.com/r-markdown-powerpoint-presentation/ How To Make A PowerPoint Presentation Using R Markdown] including How to Style Your R Markdown PowerPoint Presentation.
* [https://www.infoworld.com/article/3648458/how-to-create-powerpoint-slides-from-r.html How to create PowerPoint slides from R]


=== xaringan: presentation ===
=== xaringan: presentation ===
* https://github.com/yihui/xaringan
* https://github.com/yihui/xaringan.
** [https://slides.yihui.org/xaringan/#1 HTML Vignette/Slides].
** [https://bookdown.org/yihui/rmarkdown/xaringan.html Chapter 7 xaringan Presentations]
* [https://github.com/jtleek/jhsph-irb-research-plan-template/ R markdown template for writing these research plans]
* [https://github.com/jtleek/jhsph-irb-research-plan-template/ R markdown template for writing these research plans]
* [https://jozefhajnala.gitlab.io/r/r909-rmarkdown-tips/ Create R Markdown reports and presentations even better with these 3 practical tips]
* [https://jozefhajnala.gitlab.io/r/r909-rmarkdown-tips/ Create R Markdown reports and presentations even better with these 3 practical tips]
** Live preview of R Markdown files with xaringan’s infinite_moon_reader(). [https://yihui.name/en/2019/02/ultimate-inf-mr/ The Ultimate Infinite Moon Reader for xaringan Slides].
** Live preview of R Markdown files with xaringan’s infinite_moon_reader(). [https://yihui.name/en/2019/02/ultimate-inf-mr/ The Ultimate Infinite Moon Reader for xaringan Slides].
** The RStudio addins is available in the Addins dropdown menu under the XARINGAN (need to scroll down to the bottom since the addins are sorted alphabetically by package names).
** Creating beautiful, multi format reports directly from R scripts
** Creating beautiful, multi format reports directly from R scripts
** Advanced chunk options with useful effects
** Advanced chunk options with useful effects
Line 796: Line 1,197:
* [https://pkg.garrickadenbuie.com/xaringanExtra/#/ xaringanExtra], [https://youtu.be/vZMuu77ocMY useR! 2020] youtube video.
* [https://pkg.garrickadenbuie.com/xaringanExtra/#/ xaringanExtra], [https://youtu.be/vZMuu77ocMY useR! 2020] youtube video.
* [https://silvia.rbind.io/2021-03-16-deploying-xaringan-slides/?s=09 Deploying xaringan Slides: A Ten-Step GitHub Pages Workflow]
* [https://silvia.rbind.io/2021-03-16-deploying-xaringan-slides/?s=09 Deploying xaringan Slides: A Ten-Step GitHub Pages Workflow]
* [https://youtu.be/3n9nASHg9gc Slides with Rmarkdown: xaringan (R case study, 2021)], [https://www.youtube.com/watch?v=3n9nASHg9gc&t=1888s Speaker/presenter notes]
** [https://bookdown.org/yihui/rmarkdown/xaringan-key.html Keyboard shortcuts]. '''c''' for Clone slides to new window & '''p''' for the Presenter mode.
** In the presenter mode, there is a timer on the top right corer. It'll start with 0:00:00.
** restart the timer: '''t'''
** Next slide: Right/Down arrows, PageDown, Space, or j
** Previous slide: Up/Left arrows, PageUp, or k
** Help menu: '''h''' or '''?'''
** Slide manipulation: Black out slide: '''b'''. Mirror slide: '''m'''
** Jump to specific slide: Type '''number + Enter'''
** I use 8bitdo Ultimate Software to map some buttons.
*** Face buttons: X=t (reset timer), Y=Space (pause for YT), A=p (presenter mode), B=f (full screen).
** Flash cards - [https://quizlet.com Quizlet]
* (Video) [https://youtu.be/5ZeA-E-XIE0 rmarkdown: Make interactive PowerPoint slide presentations in R]
* Live preview/View changes in real-time: infinite moon reader
** [http://jenrichmond.rbind.io/post/infinite-moon-reader/ How to use infinite moon reader]. Open a rmd document that you are working on and in the console call xaringan::inf_mr() i.e. infinite moon reader.
** [https://bookdown.org/yihui/rmarkdown/xaringan-preview.html 7.4 Build and preview slides]
* [https://www.keanarichards.com/2021/03/19/making-a-presentation-in-r/ Making a Presentation in R: Getting started]
* Creating PDF file: [https://www.garrickadenbuie.com/blog/print-xaringan-chromote/ Printing xaringan slides]: Use "Print" function in the browser
* You can use HTML elements directly in an R Markdown file. R Markdown allows you to mix Markdown, R code, and HTML code in the same document1. You can use HTML tags to format your text, create tables, insert images, and more. For example, if I want to highlight a certain line in a code block, we can use the '''span''' element with an inline CSS to set the background color. See [https://bookdown.org/yihui/rmarkdown-cookbook/html-hardcore.html 7.15 For hardcore HTML users (*)] from [https://bookdown.org/yihui/rmarkdown-cookbook/ R Markdown Cookbook].
:<syntaxhighlight lang='html'>
<pre><code>
This is a code block
<span style="background-color:yellow">This line is highlighted</span>
</code></pre>
</syntaxhighlight>
* By default, the HTML output file depends on some CSS files and the source of any images files. To make the HTML file self contained, use either '''rmarkdown::render("your_presentation.Rmd", output_options = list(self_contained = TRUE)) ''' OR modify the YAML header.
<pre>
---
title: "My xaringan Presentation"
output:
  xaringan::moon_reader:
    self_contained: true
---
</pre>
==== Incremental slides ====
<ul>
<li>Add the following to a file "custom.css"
<syntaxhighlight lang='css'>
@media print {
  .remark-slide-content .incremental {
    opacity: 1 !important;
    visibility: visible !important;
  }
}
</syntaxhighlight>
and include the custom.css file in the Rmd yaml section
<pre>
---
title: "My Presentation"
output:
  xaringan::moon_reader
css: "custom.css"
---
</pre>
<li>To convert an xaringan HTML presentation containing incremental slides to a PDF while collapsing incremental slides:
<syntaxhighlight lang='r'>
install.packages("pagedown")
pagedown::chrome_print("your-presentation.html", output = "your-presentation.pdf")
</syntaxhighlight>
Note that using Chrome's print function results in a malformatted PDF.
</ul>
==== [https://stackoverflow.com/a/52663290 Change the background color of a code chunk] ====
Create a text file called "custom.css"
<syntaxhighlight lang='css'>
.code-bg-gray .remark-code, .code-bg-gray .remark-code * {
background-color:#e1e7e9!important;
}
</syntaxhighlight>
In the YAML section of the Rmd file, add a line '''css: [default, metropolis, metropolis-fonts, custom.css]'''.
<pre>
output:
  xaringan::moon_reader:
    css: [default, metropolis, metropolis-fonts, custom.css]
    lib_dir: libs
    nature:
      highlightStyle: github
      highlightLines: false
      countIncrementalSlides: false
    self_contained: true 
</pre>
In the code chunk, follow the instruction there by wrapping your code chunk with
<pre>
.code-bg-gray[
``` 
```
]
</pre>
==== Change the font size of a code chunk ====
This sets the font size to 0.8em, which is 90% of the parent element's font size.
<pre>
<div style="font-size: 0.9em;">
```
# My code
```
</div>
</pre>
To combine this with a gray background.
<pre>
<div style="font-size: 0.9em;">
.code-bg-gray[
```
```
]
</div>
</pre>
==== Change the font size of a table ====
<pre>
<style>
# Slide with Table
table {
  font-size: 16px; /* Set the desired font size */
}
</style>
| Task                            | Docker Command              |
|---------------------------------|-----------------------------|
| Build an image                  | `docker build`              |
| Run a container                | `docker run`                |
| Pull an image from a registry  | `docker pull`              |
</pre>


=== Create presentation file (beamer) ===
=== Create presentation file (beamer) ===
Line 975: Line 1,505:


== Publish R results ==
== Publish R results ==
[https://jozefhajnala.gitlab.io/r/r907-christmas-praise/ 5 amazing free tools that can help with publishing R results and blogging]
* [https://jozefhajnala.gitlab.io/r/r907-christmas-praise/ 5 amazing free tools that can help with publishing R results and blogging]
* [https://rpubs.com/about/getting-started Getting Started with RPubs]


== Scheduling R Markdown Reports via Email ==
== Scheduling R Markdown Reports via Email ==
Line 992: Line 1,523:
R notebook
R notebook
* It adds '''html_notebook''' in the output option in the header.  
* It adds '''html_notebook''' in the output option in the header.  
* You can then '''preview''' the rendering quickly without having to knit it (does not execute any of your R code chunks). If you manually 'Run' the chunks, the result will be shown up in preview.
* You can then '''preview''' the rendering quickly without having to knit it ('''does not execute any of your R code chunks'''). If you manually 'Run' the chunks, the result will be shown up in preview.
* It also refreshes the preview every time you save.  
* It also refreshes the preview every time you save.  
* However in that preview you don't have the code output (no figures, no tables..)  
* However in that preview you don't have the code output (no figures, no tables..)  
Line 1,156: Line 1,687:
* [https://masalmon.eu/2020/02/29/hugo-maintenance/ What to know before you adopt Hugo/blogdown]
* [https://masalmon.eu/2020/02/29/hugo-maintenance/ What to know before you adopt Hugo/blogdown]
* [https://ropensci.org/blog/2020/04/07/bookdown-learnings/ 10 Things We Learned in Creating the Blog Guide with bookdown] 2020
* [https://ropensci.org/blog/2020/04/07/bookdown-learnings/ 10 Things We Learned in Creating the Blog Guide with bookdown] 2020
* [https://yihui.org/en/2022/06/user-blogdown/ My Talk at useR! 2022 on blogdown]


== bs4cards: an R package for bootstrap 4 cards ==
== bs4cards: an R package for bootstrap 4 cards ==
Line 1,165: Line 1,697:
== portfoliodown ==
== portfoliodown ==
[https://www.business-science.io/code-tools/2021/12/20/portfoliodown.html Introducing portfoliodown: The Data Science Portfolio Website Builder]
[https://www.business-science.io/code-tools/2021/12/20/portfoliodown.html Introducing portfoliodown: The Data Science Portfolio Website Builder]
== distill ==
[https://book.rwithoutstatistics.com/websites-chapter.html 10 Make Websites to Share Results Online] from the ebook '''R Without Statistics'''
== flexdashboard ==
* https://pkgs.rstudio.com/flexdashboard/
* [https://ivelasq.rbind.io/blog/automated-youtube-dashboard/ Using flexdashboard to create a GitHub Actions-powered YouTube feed]


= Pagedown =
= Pagedown =
Line 1,178: Line 1,717:
</pre>
</pre>


= postcards =
= postcards: personal/landing page =
[https://github.com/seankross/postcards postcards] - Create simple, beautiful personal websites and landing pages using only R Markdown.
[https://github.com/seankross/postcards postcards] - Create simple, beautiful personal websites and landing pages using only R Markdown.


Line 1,201: Line 1,740:
= Quarto =
= Quarto =
* https://quarto.org/
* https://quarto.org/
** File extension name is qmd. [https://quarto.org/docs/get-started/hello/rstudio.html Tutorial: Hello, Quarto]
** [https://quarto.org/docs/tools/rstudio.html Quarto - RStudio IDE], [https://quarto.org/docs/get-started/hello/rstudio.html Quarto - Tutorial: Hello, Quarto], [https://quarto.org/docs/get-started/computations/rstudio.html Tutorial: Computations]
** [https://quarto.org/docs/guide/ Guide], [https://quarto.org/docs/computations/r.html Using R]
** [https://quarto.org/docs/faq/rmarkdown.html FAQ for R Markdown Users]
* [https://www.jumpingrivers.com/blog/quarto-rmarkdown-comparison/ I'm an R user: Quarto or R Markdown?]
* [https://dirk.eddelbuettel.com/blog/2022/01/31/#035_apt_install_rstudio_quarto #35: apt install rstudio quarto] Eddelbuettel
* [https://dirk.eddelbuettel.com/blog/2022/01/31/#035_apt_install_rstudio_quarto #35: apt install rstudio quarto] Eddelbuettel
* [https://youtu.be/y5VcxMOnj3M Create beautiful documents with Quarto and R] (video)
* [https://youtu.be/shVSmYna3GM R-Ladies Freiburg (English) - Getting to know Quarto] (video) 2022/6/3
* [https://youtu.be/yvi5uXQMvu4 Welcome to Quarto Workshop!] (video) Tom Mock 2022/8/9
* [https://github.com/analythium/quarto-docker-examples Quarto Examples with Docker]
* [https://twitter.com/mattdray/status/1555610784406855683?s=20&t=Xe3aXGwh0-CHLdXfKaEb5w quartostamp] RStudio Add-in package
* [https://twitter.com/MeghanMHall/status/1573365069093937155?s=20&t=f71qFzNbqErKI0omM2dWCQ Parameterized reporting with Quarto in R]
* [https://nrennie.rbind.io/blog/parameterized-plots-reports-r-quarto/ Parameterized plots and reports with R and Quarto]
* [https://medium.com/number-around-us/arming-your-data-spaceship-essential-quarto-tips-and-tricks-for-the-modern-explorer-ead0fa787adb Arming Your Data Spaceship: Essential Quarto Tips and Tricks for the Modern Explorer]. [https://quarto.org/docs/interactive/layout.html Tabs], [https://davidgohel.github.io/ggiraph/ ggiraph] for interactive ggplot2., [https://quarto.org/docs/authoring/footnotes-and-citations.html#footnotes footnote], [https://quarto.org/docs/authoring/diagrams.html mermaid/graphviz diagrams].
* [https://www.r-bloggers.com/2025/05/repost-writing-a-book-with-quarto/ Repost: Writing a book with Quarto]
* [https://posit.co/blog/create-a-quarto-document-in-positron/ Create a Quarto Document in Positron]
== Visual editor ==
[https://stackoverflow.com/a/72360483 Disable visual markdown editor on RStudio]
== Quarto dashboard ==
* https://quarto.org/docs/dashboards/
* [https://www.r-bloggers.com/2024/03/building-a-malaysian-population-dashboard-with-quarto-in-r/ Building a Malaysian Population Dashboard with Quarto in R]
== Quarto live ==
[https://rtichoke.netlify.app/posts/quarto_live.html Explore Neural Networks Interactively with Quarto Live!]
= parsermd =
https://rundel.github.io/parsermd/. The goal of parsermd is to extract the content of an R Markdown file to allow for programmatic interactions with the document’s contents (i.e. code chunks and markdown text).

Latest revision as of 09:10, 16 November 2025

Markdown language

According to wikipedia:

Markdown is a lightweight markup language, originally created by John Gruber with substantial contributions from Aaron Swartz, allowing people “to write using an easy-to-read, easy-to-write plain text format, then convert it to structurally valid XHTML (or HTML)”.

  • Markup is a general term for content formatting - such as HTML - but markdown is a library that generates HTML markup.

Editors

Why You Should Be Writing Everything in Markdown 2023/10/11.

Github markdown Readme.md

How to nest code within a list using Markdown

https://meta.stackexchange.com/questions/3792/how-to-nest-code-within-a-list-using-markdown

Continuous publication

Open collaborative writing with Manubot Himmelstein et al 2019

Syntax

Comment: https://stackoverflow.com/questions/4823468/comments-in-markdown. The html method does not work. I need to try use Shift+ CMD + c.

Table

Simple example

| Column 1       | Column 2     | Column 3     |
| :------------- | :----------: | -----------: |
|  Cell Contents | More Stuff   | And Again    |
| You Can Also   | Put Pipes In | Like this \| |

Include code

Markdown Code Block: Including Code In .md Files

  • Inline code blocks:
    Use `print("Hello, world!")` to print a message to the screen.
    
  • Fenced code blocks:
    ```python
    print("Hello, world!")
    for i in range(10):
        print(i)
    ```
    
  • Indented code blocks
    Here's some regular text. And now a code block:
    
        print("Hello, world!")
        if True:
            print('true!')
    

Literate programming

Rmarkdown

HTML5 slides examples

Software requirement

Slide #22 gives an instruction to create

  • regular html file by using RStudio -> Knit HTML button
  • HTML5 slides by using pandoc from command line.

Files:

  • Rcmd source: 009-slides.Rmd Note that IE 8 was not supported by github. For IE 9, be sure to turn off "Compatibility View".
  • markdown output: 009-slides.md
  • HTML output: 009-slides.html

We can create Rcmd source in Rstudio by File -> New -> R Markdown.

There are 4 ways to produce slides with pandoc

  • S5
  • DZSlides
  • Slidy
  • Slideous

Use the markdown file (md) and convert it with pandoc

pandoc -s -S -i -t dzslides --mathjax html5_slides.md -o html5_slides.html

If we are comfortable with HTML and CSS code, open the html file (generated by pandoc) and modify the CSS style at will.

Tips

Debug

Debugging RMarkdown

YAML

  • ymlthis package - write YAML for R Markdown, bookdown, blogdown, and more.
  • R Markdown Crash Course YAML Headers

Some examples

---
title: "My Title"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  pdf_document:
    toc: true
    number_sections: true
classoption: landscape    
---
---
title: "My Title"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output: latex_document
---

Debug by keep tex

Rmarkdown Retain .tex file. We can use this technique to see what goes wrong in the middle step.

output:
  pdf_document:
    keep_tex: true
---

HTML output

Useful YAML options for generating HTML reports in R

HTML Turn off title

Rmarkdown: Turn off title

HTML with dynamic table of contents

---
title: "My title"
output: 
  rmdformats::robobook: 
    highlight: tango
    number_sections: true
    lightbox: true
    gallery: true
    code_folding: hide
---

Inlcude latex packages

render(, params)

---
title: "Homework"
output:
  html_document:
    code_folding: hide
    toc: true
    toc_float: true
    theme: "flatly"
params:
  run: TRUE
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = params$run)
```

```{r chunk1}
dim(iris)
```

We can use the following command to create an html file that does not evaluate the code for the whole document.

rmarkdown::render("Homework.Rmd",
          params=list(run = FALSE), 
          output_file = "Homework.html")

Code folding

Center title in html output

How do I center my YAML heading in an R markdown html document? Use CSS styling.

Office (Word, Powerpoint) output

Examples

ComBatCorr, Preview HTML

---
title: "..."
author: "..."
output:
  html_document:
    code_folding: hide
    toc: true
    toc_float: true
    theme: "flatly"
editor_options: 
  chunk_output_type: console
---

PDF output

---
title: "..."
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  pdf_document:
    toc: true
    toc_depth: 3
    number_sections: true
    fig_caption: true
urlcolor: blue
---

Chunk options

Some options:

  • echo=FALSE. whether to include R source code in the output file
  • message=FALSE. whether to preserve messages emitted by message() (similar to warning)
  • results = 'hide'. hide results; this option only applies to normal R output (not warnings, messages or errors) like print() or cat().
    • Note: if we spell the option incorrectly like result = 'hide' , the 'R markdown' window from running knitting will not show any warnings and the purpose of hiding the print result will not work either.
  • include. whether to include the chunk output in the final output document;
  • warning. whether to preserve warnings (produced by warning()) in the output like we run R code in a terminal (if FALSE, all warnings will be printed in the console instead of the output document). This seems to be useful. Too many warnings will make the computation time much longer (eg. 3 hours vs 30 minutes) no to say the output file will be very large.
  • error. whether to preserve errors (from stop()); If you want to show the errors without stopping R, you may use the chunk option error = TRUE. See Do not stop on error
  • comment. Remove Hashes in R Output from R Markdown and Knitr
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, cache = TRUE, warning = FALSE, 
                      message = FALSE, verbose = FALSE)
```

Global options