class: center, middle, inverse, title-slide # R Markdown and Packages ## Psychology as a Science: Practical 3 --- # Plan for today - Knitting documents - Editing documents meta-data (through YAML) - Markdown basics - Interacting with **R Studio** - The **console** - Code chunks - **Knitting** with **code chunks** - Installing and loading **packages** - Using the `here` package - Using the `here` package to insert images --- <div class = "middle">Interacting with <b>RStudio</b></div> --- # Knitting documents The **R Markdown** document we're working on doesn't look very pretty, -- but there is a way to turn it into a pretty document. -- This process of going from **R Markdown** to **pretty document** is called **knitting** .pull-left[ ![](https://github.com/ljcolling/my_images/raw/master/markdown.png) ] .pull-right[ ![](https://github.com/ljcolling/my_images/raw/master/knitr.png) ] To **knit** an **R Markdown** document into something pretty click on the **Knit** button ![](https://github.com/ljcolling/my_images/raw/master/knitr_icon.png) --- ![](https://github.com/ljcolling/my_images/raw/master/rmarkdown_overview.png) **Knitting** your **R Markdown** document turned it into a **"knitted"** document. Try **knitting** your document and see what happens. --- <div class="middle">Setting the meta-data on your <b>knitted</b> document…</div> --- # YAML (rhymes with camel) header At the top of your **R Markdown** document will be a header which should look something like the follows: ``` --- title: "Untitled" output: html_document --- ``` It stores **meta-data** about your document. Using the YAML heading you add information about the **title** of your document, the **author**, and the **date**. Trying adding some of your own information like so: ``` --- title: "My fancy title" author: "Me" date: "01/01/2001" output: html_document --- ``` .red[Note:] The last line (`output: html_document`) determines what kind of document is produced when you click **knit**. We're knitting to an Html document, but you can also **knit** to an MS Word document, a PDF, and many more (including these slides!). For now, we'll just always keep the last line as is. --- # Try it! Trying clicking **knit** to produce the **knitted** document, and play around with changing the **title**, **author**, **date** etc. Re-**knit** the document to see how the **knitted** document changes. --- <div class="middle">Formatting text</div> --- # Formatting with Markdown We can format the documents we write in **RStudio** with something called ** markdown** **Markdown** uses characters to add formatting <u>**Some simple markdown**</u> Sometimes we will want to make words **bold** or write them in *italics*. We can do this in markdown by using the `*` symbol. - To format a word in *italics* you just put `*` on either side of the word, e.g., `*italics*` - To make a word in **bold** you just put `**` on either side of the word, e.g., `**bold**` You can do a lot more in markdown than just bold and italics, but we'll just go through some of the basics. Check out the [R Markdown cheatsheet](https://rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf) for more! --- # Starting fresh… When you create an **R Markdown** document **RStudio** often fills in some *default* content. Let's delete everything **below** the red line so that can start with a fresh document. ![](https://github.com/ljcolling/my_images/raw/master/below_red_line.png) As we go through the **R Markdown** basics, feel free to add stuff to your document… --- # Headers Headers are marked with the `#` symbol. -- .pull-left[ #### Markdown - `# Level 1 heading` - `## Level 2 heading` - `### Level 3 heading` ] -- .pull-right[ #### Knitted text - # Level 1 heading - ## Level 2 heading - ### Level 3 heading ] --- # Unordered lists Unordered lists use `*`, and `+`, and `-` to mark items and spaces to define levels. -- .pull-left[ #### Markdown ``` * This is the first bullet point + this is a sub-bullet + this is another sub-bullet * This is the second bullet point + this is another sub-bullet - this is a sub-sub-bullet ``` ] -- .pull-right[ #### Knitted text * This is the first item + this is a sub-item (indented with four spaces) + this is another sub-item * This is the second item + this is another sub-item - this is a sub-sub-items (indented with six spaces) ] --- # Ordered lists Ordered lists use `1.` to mark items and spaces to define levels. -- .pull-left[ #### Markdown ``` 1. This is the first bullet point 1. this is a sub-bullet 1. this is another sub-bullet 1. This is the second bullet point 1. this is another sub-bullet 1. this is a sub-sub-bullet 1. this is another sub-bullet ``` ] -- .pull-right[ #### Knitted text 1. This is the first bullet point 1. this is a sub-bullet (4 spaces) 1. this is another sub-bullet 1. This is the second bullet point 1. this is another sub-bullet 1. this is a sub-sub-bullet (6 spaces) 1. this is another sub-bullet ] --- ## Emphasis and sub/superscript You can also format text to be **bold**, *italics*, and more… -- .pull-left[ #### Markdown ``` *italics* **bold** superscript^text^ subscript~text~ ~~strikethrough~~ ``` ] -- .pull-right[ #### Knitted text *italics* **bold** superscript<sup>text</sup> subscript<sub>text</sub> ~~strikethrough~~ ] --- # More R Markdown There's more that we can do with **R Markdown** including -- - Adding **hyperlinks** to documents -- - Adding **images** to documents -- To learn more check out the [**R Markdown** cheatsheet](https://rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf). -- In **Part II** we'll learn how to **insert images**, but we first need to learn more about the `here` package. --- <div class="middle">End of Part I</div> --- <div class="middle">Computer Quiz</div> --- <div class="middle">Part II</div> --- <div class="middle">Interacting with <b>RStudio</b></div> --- # Interacting with RStuido There are two main ways of interacting with **RStudio**. .pull-right-big[ ![](https://github.com/ljcolling/my_images/raw/master/console_and_source.png) The **Console** and **Source** pane ] .pull-left-small[ - The **Console pane** - **Code chunks** in the **Source pane** ] --- # Using the Console We can use **RStudio** as a calculator by typing commands into the **Console** window. ![](https://github.com/ljcolling/my_images/raw/master/typing_a_command.png) --- <div class="letsdo">Let's try typing some simple sums into the console</div> --- # Using the Console -- - Typing commands into the console is an easy way to do a **quick check** of a command -- - But it's a **terrible** do type the commands for an **analysis** directly into the console -- Using the **console** doesn't keep a **saveable record** of your commands, which isn't very useful in case you want to **re-run** or **reproduce** the analysis! -- But it is useful if we want to run a command <u>just once</u>, so we'll use the console for **installing packages** later in the practical. -- Instead, you can use your **R Markdown** document to store your commands! -- We can use special parts of the **R Markdown** document called a **Code chunk** to store and organise our **commands** --- # Using code chunks -- Code chunks are like little console windows that live in our **R Markdown** document. -- **Code chunks** are **fenced** off using <code>```{r}</code> at the start -- and <code>```</code> at the end -- ![](https://github.com/ljcolling/my_images/raw/master/code_chunk_carbon.png) An example of a **fenced** off code chunk. --- # Naming code chunks **Code chunks** can also be given names -- ![](https://github.com/ljcolling/my_images/raw/master/code_chunk_carbon_named.png) An example of a **code chunk** that has been *named* `code_chunk_name` --- # Creating code chunks To create/insert a new code chunk: - **Code** > **Insert Chunk** - ctrl + alt + i (Windows) / cmd ⌘ + opt ⌥ + i (Mac) Try inserting a new code chunk somewhere near the end of your document. <code>```{r}</code> <code>```</code> -- Now let's call our code chunk `cars`, -- and then add some code… <code>```{r cars}</code> `summary(cars)` <code>```</code> For now, it doesn't matter what the command `summary(cars)` does. All that matters is that it produces some output. --- <div class="letsdo">Let's try creating a code chunk</div> --- # Running a code chunk ![](https://github.com/ljcolling/my_images/raw/master/cars_code_chunk.png) The code chunk named `cars` -- When you type commands into the **console** they run as soon as you hit ENTER. -- But to run **code chunks** you have to click on the **run** button. -- ![](https://github.com/ljcolling/my_images/raw/master/cars_code_chunk_zoomed.png) The **run** button for a **code chunk** -- Trying clicking the **run** button and seeing what it does… -- Now try typing `summary(cars)` into the console… -- You should get the same output (although maybe formatted slightly differently) --- # Knitting with code chunks When you **knit** a document that has **code chunks** in it, then **R Studio** first **runs** all the **code chunks** -- Try **knitting** your **R Markdown** document and seeing what happens with your code chunk. -- .pull-left[![](https://github.com/ljcolling/my_images/raw/master/r_markdown_code.png) **R Markdown** document with **code chunks**] -- .pull-right[![](https://github.com/ljcolling/my_images/raw/master/r_markdown_code_knitted.png) **Knitted** document ] -- Your knitted document will show: - The content of the code chunk - The output of the code chunk --- # Code chunk options By default, the **content** and the **output** of our **code chunks** will be included in the **knitted** document. -- But we don't always **want this** - `echo=FALSE`: the code will be run but not reproduced in the knitted document - `eval=FALSE`: the code will not be run - `include=FALSE`: the code will be run, but neither the code nor output are displayed in the knitted document - `results="hide"`: the code will be run and displayed in the knitted document, but the output will be omitted - `results = 'asis'` when creating tables from code/output --- # Code chunk options **Manually setting chunk options** You can specify the chunk options after the chunk name (separated from the chunk name with a comma) <code>```{r cars, echo=FALSE}</code> `summary(cars)` <code>```</code> -- **Using the chunk options menu** You can also click on the gear icon to access a **chunk option** menu. ![](https://github.com/ljcolling/my_images/raw/master/gear_and_run.png) Try changing the code chunk options and **re-knitting** the document to see what happens. --- <div class="letsdo">Let's try changing the chunk options and seeing what changes</div> --- <div class="middle">Installing packages</div> --- # Installing and loading packages ![](https://github.com/ljcolling/my_images/raw/master/packages.png) -- - **Packages** are add-ons that you can install to extend the functionality of **R**. -- For example, some packages might let you do new kinds of **analyses** or draw new kinds of **figures** -- - **CRAN** (The <u>C</u>omprehensive <u>R</u> <u>A</u>rchive <u>N</u>etwork) is a **repository** of the main **R** packages -- - Before you can **use** a **package** you will need to **install** onto your computer --- # Installing and loading packages - Before you can **use** a **package** you need to install it from CRAN - If you use multiple computers, then you'll need to **install** that **package** onto <u>every</u> computer that you use **Installing a package from CRAN** There are two main ways to install a package in **RStudio** 1. `install.packages(package_name)` 2. Tools > Install Packages... **Loading a package** Once a **package** has been installed you can use it with - `library(package_name)` You only need to **install** a package **once** so we type the command into **Console**. But you need to **load** a package **every time**, so we put these commands into **Code chunks** --- # Using packages **Packages** give you access to **extra** commands (these are technically called *functions*) - Last week I showed you a function called `here` for giving directions to files from **HERE** - the `here` command is from a package called `here` - to use the `here` command, we first have to install the `here` package --- # Installing the `here` package To **install** the `here` package type the command `install.packages("here")` into the **Console** .red[Note:] Remember to include the double quotes (`""`) around the word **here** ``` > install.packages("here") trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/here_0.1.zip' Content type 'application/zip' length 20513 bytes (20 KB) downloaded 20 KB The downloaded binary packages are in C:\Users\lincoln\AppData\Local\Temp\RtmpGQFj9z\downloaded_packages > ``` .pull-left[After the `here` package has been installed you can see what functions are included in the package by typing `here::` into the **console**] .pull-right[![](https://github.com/ljcolling/my_images/raw/master/pacakge_popup.png)] --- # Using the `here` package Now that the **here** package is **installed** we will be able **use** it. We will want to use it in our **R Markdown** document, so let's add a command to **load** it into our **R Markdown** document. We'll use the **code chunk** named **setup** for loading packages. -- Find the **code chunk** named **setup** (it should be the very first one) ![](https://github.com/ljcolling/my_images/raw/master/setup_chunk.png) --- # Using the `here` package Let's add the command `library(here)` to the third line of the setup code chunk. ![](https://github.com/ljcolling/my_images/raw/master/setup_chunk_with_here.png) -- We will use our **setup** chunk for a few different things including setting *global options*, *loading packages*, and *loading data* We'll group each *set* of tasks together and separate them with a blank line. --- # Using the `here` package - After you load a package using the `library` command, then all the commands associated with that package will be imported (which means you can use them) - Let's make sure the **here** package is loaded by typing the command to load it into the **console** window -- To load the **here** package so that it's ready to use, type: ``` > library(here) ``` Now let's try using the `here()` command by typing it into the **console** ``` > here() ``` When you run the command, it should print out the **path** of your **project folder** --- # What's the `here` package for? We can use the `here` package to help us **refer** to files. We'll use this extensively when we're referring to data files, but we can also use it for referring to **images** that we want to embed in your **R Markdown** document. <u>Downloading an image</u> - First, create a new **sub-folder** in your project folder called **images** - Then right-click on [this link](http://paas.mindsci.net/images/paas.png) and save the target to the **images** sub-folder in your **project folder** - Navigate to your **images** sub-folder in your **Files** pane so that you can make sure you know the **filename** of your image file (include the extension) --- # Images .pull-left[ The basic format for including figures is `![Cap text for img](image_file)` e.g., `![The rstudio logo](logo.png)` ] .pull-right[ ![The studio logo](https://github.com/ljcolling/my_images/raw/master/RStudio-icon.png) ] When you want to insert an image, you need to know the **file path** of, or the directions to, the image you want to insert… But file paths are **difficult**, so we're going to use the **here** package for help! -- And we'll use a special thing called an **inline code chunks** --- # Inline code chunks Usually we fence off code chunks using off using <code>```{r}</code> at the start and <code>```</code> at the end - Fenced off code chunks are used to **separate** our **code** and our **text** - But sometimes we want to **mix** our **code** with our **text**! - For an inline code chunks you simple put your code between <code>`r `</code> - The inline code chunk is replaced with the output of the command when you **knit** the document .pull-left[ If you wrote: <code>1 + 1 = `r 1 + 1`</code> ] -- .pull-right[ It would appear as: <code>1 + 1 = 2</code> ] -- We can use this trick almost anywhere, including, for example, when trying to include images… -- Try to include an image in your **R Markdown** document, but instead of writing the file path try using the **here** package to write the file path for you. --- # Inline code chunks and images If you wrote `![]`<code>(`r here::here("images","paas.png")`)</code> Then that line would first be transformed into `![](c:/Users/Lincoln/Documents/my_paas_project/images/paas.png)` and then into .pull-left[![](https://github.com/ljcolling/my_images/raw/master/space_pirate.png)] --- # Next week Next week we're doing to be learning about **data** and **data file** We'll using a **collection** of **packages** called the `tidyverse` To prepare for next week let us all install the `tidyverse` ``` > install.packages("tidyverse") ``` #### At home activity for next week Do the final section of the interactive tutorial and watch the video linked on the [Week 4 Canvas page](https://canvas.sussex.ac.uk/courses/10404/pages/week-4) -- And remember to **log out** of the computers!