---
title: "IV.\\ R Markdown (exercises)"
author: "Data Science Lab, University of Copenhagen"
date: today
format: 
  pdf:
    toc: true
    toc-depth: 3
    toc-location: left    
    embed-resources: true
execute:
  echo: true
---


R Markdown is a file format for making dynamic documents that integrate code, output, graphs and text. Actually, all the html and pdf documents for the course have been generated with R Markdown. This exercise will get you started and show a few of the many, many features with R Markdown. You can find a cheatsheet inside the RStudio menu: *Help* &#8594; *Cheat Sheet* &#8594; *R Markdown Cheat Sheet*.

## Quarto files, rendering 

1. Open a new R Markdown document (*File* &#8594; *New File* &#8594; *Quarto Document*). If you are asked to install some extra packages, then answer "yes". You are asked for a title; just write *Test* or whatever you want. Choose html as output format. Save the document; use file extension .Rmd, if you do not let the computer choose it for you.

2. Verify that you can *render* the document with the example content: Click on the ***Render*** button in the console toolbar, and an example output file should be generated. 

3. Edit the title of the markdown document to *My first Quarto document*, and click ***Render*** again. Notice how the title of the output document changes.

Notice that, as soon as the output html file is generated, you can view it with any browser (without starting RStudio). Your work is therefore easily shared with collaborators who do not use R themselves. 

## R chunks and text

4.  Delete the example content in the markdown document from the first hashtag and down. Insert a new R chunk by clicking on the *Insert* button in the console toolbar (the button with a white *C* in a green square), and choosing *R*. Then, type (for example)

    ```{r}
    #| eval: false
    3+2
    log10(0.001)
    z <- 17
    ```
    
    inside the chunk. Don't render yet! Instead: What happens when you click the little green "play" button to the right of the chunk? 

5.  You can also run each line one at a time with *Ctrl + Enter* as usual. Try it. 

As you may already have noticed, it takes a few seconds to render your document, even if it is very small. It is therefore recommended that you **run your R commands/chunks without rendering until you they are roughly as they should be**. You just saw how to do that. 

6. Render the document, and notice what the R chunk has now generated. 

7. Click the small wheel next to the R chunk, and select *Show output only* in the dropdown menu denoted *Output*. Notice how the R chunk changes. Render the document, and notice what happens in the output. Obviously, the different options can be used to control the output from an R chunk. (There are more possibilities then shown in the drop down menu; they can be obtained with options `echo`, `include` and `eval`). You may switch back to *Use document defaults* again.    

8. Add the text *Some simple computations in R* above the chunk, and knit the markdown document again.

9.  Insert a line above the text, starting with two hashtags and followed by some text, e.g. `## My header`. Render, and see what happens. 

10. Insert a chunk with the following code, knit, and see what happens:

    ```{r}
    #| eval: false
    x <- c(1,2,3,4)
    y <- c(2,6,3,1)
    plot(y ~ x)
    ```

### Word or pdf output

11. Notice the line `format: html:` in the beginning of the qmd file. It implies that output is written to a html file. If you have MS Word installed, then it is easy to have the output generated as a docx file instead: Simply write `docx` instead of `html`. Try it!

12. If you prefer pdf-output, you write `pdf`. You need to install a version of the TeX program at your computer first. If you do not use LaTeX for other things, then it is recommended to use ***TinyTeX***, which is a "lightweight" version of LaTeX. This can be done from inside RStudio:

    ```{r}
    #| eval: false
    install.packages('tinytex') # Install package
    tinytex::install_tinytex()  # install the program
    ```
    
    Notice that it is likely necessary to restart you PC after the installation. Furthermore, if you have a Windows PC, then it is likely necessary to have Rtools installed for this, see https://cran.r-project.org/bin/windows/Rtools/.
    
    **Warning:** If you already have a TeX-installation, e.g. ***MikTeX***, then don't install ***TinyTeX***. If you do, then the TeX installations might be in conflict.

<!-- 
That should work readily on the ERDA system. If you work locally on your laptop, then you need to install a version of the TeX program at your computer: MiKTeX til Windows, MacTeX til mac. If you knit without having TeX installed, then you probably get an error message which includes links for installation of TeX. You must restart RStudio when you have installed TeX (before you can knit to pdf).

Notice that, for MiKTeX it says that it is important to choose _Complete_ rather than _Basic_ installation, but that appears not to be possible. Fortunately, the problem can be fixed: When you are asked if you want to _Install packages on the fly_, then answer _Yes_ rather than _Ask me first_.  
-->



## Advice and good practice

* Do not knit all the time. Instead, run code lines and R chunks without knitting while you are figuring out how they should be. 

* Do not put all your R commands into one big R chunk. Instead, split it into well-defined smaller chunks, which you may even give names. 

* The code in Rmd file must be self-contained in the sense that you cannot use datasets (or other objects) that you have imported "outside" the Rmd file. You therefore have to include the commands for data import in the file.  

* If no output is generated, then read the error message. It is not always easy to read for a beginner, but at least you are informed where the problem occurs. If you google the error message, or ask a chatbot, then you will often get information about how to handle it.

* It is possible to "cache" R trunks such that the commands are not rerun every time you knit. This is a nice feature if you have time-consuming computations. 

* As always: Make sure to organize your file in an appropriate way, save the file often, and make sure to save only relevant commands (not all the stuff you played around with at preliminary stages). 

* You can open the files in other programs than RStudio, e.g. your favorite browser for html files or your favorite pdf viewer for pdf files.

* We really just scratched the surface here - there are almost endless possibilities with R Markdown, when it comes it creating documents. You can write presentations and books in R Markdown, and you can control the many, many aspects of the layout. See, for example, _R Markdown: The Definitive Guide_ by Xie, Allaire, and Grolemund. An online version is available here: https://bookdown.org/yihui/rmarkdown/.

* A few years ago, Quarto was released as a successor to Rmarkdown. It supports other programming languages than R more easily, it is more flexible regarding output formats, and it has a visual editor, just to mention some of the differences. Most Markdown documents will also run with Quarto. 

**End of exercise**
