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+CiAgaDEgeyBmb250LXNpemU6IDE4cHggfQogIGgyIHsgZm9udC1zaXplOiAxNXB4IH0KPC9zdHlsZT4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