This document presents usual steps to convert a R file to a Rmd file.

1 - Open RStudio

2 - Open your R file (with .R extension)

It may contain :

(run all the lines to see)

3 - Open a Rmd file

using File > New File > Rmarkdown

Two options :

A Rmarkdown file is structured with :

Note : To insert chunk, use Code > Insert chunk, or the shortcut (CTRL + ALT + I)

There are many options to customize chunks. A guide can be found at https://bookdown.org/yihui/rmarkdown/.

4 - First rendering

4.1 - Copy paste all the R file content into a Rmd chunk

4.2 - Knit it !

to see a first rendering, by pressing the Knit button

Notes :

  • It creates a new file with html extension, with the same file name as the Rmd
  • Warning : If output file already exists, it will be overwritten

Observations :

  • Good traceability
  • All figures are there
  • One single output file : easily shareable

5 - Second rendering

5.1 - Split chunks and comments

5.2 - Run each chunk

We can :

  • appropriate the code by adding comments
  • explain figures

5.3 - Knit it !

6 - Third rendering

6.1 - Add formatting

Comments are formatted in markdown (R-markdown !) :

  • add titles using # (first level), ## (second level) … up to 6 !
  • make italic text : *italic text* or (_italic text_)
  • make bold text by wrapping it within two asterisks : **bold text**
  • and more : https://www.markdownguide.org/cheat-sheet/

6.2 - Knit it !

7 - Fourth rendering

7.1 - Programming good pratice

In order of appearance :

  • meaningful title
  • current date : knitting date, to remember when the analysis was done
  • explain goal of the document
  • add .libPaths() to track the location of libraries
  • load environment : libraries, global variables (eg. paths)… Group everything at the beginning of the script to see what will be needed !
  • load data
  • track libraries of origin for each function using package::function syntax instead of function, because some packages name their functions the same (eg. filter function)
  • summarize the environment with sessionInfo() as the last line, in the last chunk

7.2 - Knit it !

Waouh !

8 - In practice

In practice, we start with a pre-filled Rmarkdown document, and add headers, codes, comments and formatting while progressing in the analysis. Programming best pratices should be applied while working, and not in the end…

LS0tCnRpdGxlOiAiUiB0byBSbWQiCm91dHB1dDoKICBodG1sX2RvY3VtZW50OgogICAgY29kZV9kb3dubG9hZDogdHJ1ZQogICAgbnVtYmVyX3NlY3Rpb25zOiB0cnVlCi0tLQoKCjxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+CiAgaDEg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