This document presents usual steps to convert a R file to a Rmd
file.
- Open RStudio
- Open your R file
(with .R extension)
It may contain : - call to libraries - comments - code to load data -
code to modify data - code to make figure (run all the lines to see)
- Open a Rmd file
using File > New File > Rmarkdown
Two options :
- Create empty document to start from scratch
- Name and save the document to start from a pre-filled Rmarkdown
(useful !)
A Rmarkdown file is structured with :
- header : many options are possible to customize style
- chunks to write with programming language
- empty space between chunks to write in natural
language
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/.
- First rendering
- Copy paste all the
R file content into a Rmd chunk
- 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
- Second rendering
- Split chunks and
comments
- Run each chunk
We can :
- appropriate the code by adding comments
- explain figures
- Knit it !
- Third rendering
- Knit it !
- Fourth rendering
- 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
- …
- 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+CiAgaDEgeyBmb250LXNpemU6IDE4cHggfQogIGgyIHsgZm9udC1zaXplOiAxNXB4IH0KPC9zdHlsZT4KC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