---
title: "IV.\\ R Markdown (exercises)"
author: "Data Science Lab, University of Copenhagen"
date: "August 2025"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(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*.

### Markdown files, knitting 

1. Install the `rmarkdown` package via the _Packages_ menu or with the command 
    ```{r, echo=TRUE, eval=FALSE}
    install.packages("rmarkdown")
    ```

2. Open a new R Markdown document (*File* &#8594; *New File* &#8594; *R Markdown*). 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.

3. Verify that you can knit the document with the example content: Click on the *Knit* button in the console toolbar (it is the one with the blue wool and knitting needles), and an example output file should be generated. 

4. Edit the title of the markdown document to *My first Markdown document*, and click *Knit* 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

5. 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 results="hide"}
    3+2
    log10(0.001)
    z <- 17
    ```
inside the chunk. Don't knit yet! Instead: What happens when you click the little green "play" button to the right of the chunk? 

6. 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 knit your document, even if it is very small. It is therefore recommended that you **run your R commands/chunks without knitting until you they are roughly as they should be**. You just saw how to do that. 

7. Knit the document, and notice what the R chunk has now generated. 

8. 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. Knit 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`, `results`, and `eval`). You may switch back to *Use document defaults* again.    

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

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

11. Insert a chunk with the following code, knit, and see what happens:
    ```{r, eval=FALSE, echo=TRUE}
    x <- c(1,2,3,4)
    y <- c(2,6,3,1)
    plot(y ~ x)
    ```

### Word or pdf output

12. Notice the line `output: html_document` in the beginning of the Rmd 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 `word_document` instead of `html_document`. Try it!

13. If you prefer pdf-output, you write `pdf_document`. 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, echo=TRUE}
    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/.

<!-- 
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**
