install.packages("tidyverse")
install.packages("emmeans")
install.packages("plotly")
install.packages("cowplot")R setup
Getting started in R
R is a statistical language and computing platform that is widely used in the sciences. It is free and open source. We will be using it extensively. There are many resources available, including:
- Your notes and course material from H1 Maths and Data Science (also on Brightspace > Practicals)
- Courses such as those from Software Carpentry or Swirl
- Online videos such as IQUIT R
Use these resources as needed to complement, revise, and reinforce the concepts you’ll learn during this course.
During the practicals, use ‘copy-and-paste’ thoughtfully. R is best learned through your fingers, and working through errors, though frustrating, is an essential skill.
RStudio Projects
Working in a ‘Project’ within RStudio is the best way to avoid working directory complications. This is a very common source of frustration and errors. It also helps organize work to ensure that necessary scripts, documents, data, and output are all contained within the same folder. Other benefits include tracking your history of R commands and integrating cleanly with more sophisticated version control (e.g., git – more to come later).
Create an R Project
We will create an R Project for the semester. During each practical, you should work within this project. To set up a new project as we need it:
- Sign into OneDrive, then open RStudio
- Select File > New Project…
- Choose New Directory > New Project
- Set the Directory name as H2SMS and use the Browse button by Create project as a subdirectory of: to set a convenient location in your OneDrive folder. Click ‘Create Project’.
- In the Files panel in RStudio, click the New Folder button and create a folder called data.
- On Brightspace, download H2SMS_practicalData.xlsx in Practicals and move it into your newly created data folder.
- Close RStudio (to learn how to open appropriately)
The code in the practicals assumes this organization. If you choose to put your data files elsewhere, you will need to update the scripts accordingly. You’re now prepared and organized for a semester in R!
Opening R
When using a project, you should open R via the .proj file – not the script you plan to work on.
I repeat: Open H2SMS.Rproj instead of the .R or .qmd file you plan to work on!
Opening the .R or .qmd from Windows Explorer will not set your R working directory correctly!
This is the start-up process you should use for the practicals:
- Open Windows Explorer (or Finder on Mac) and find your H2SMS folder.
- Double click on H2SMS.Rproj. This opens your R project with the working directory set to that folder. The working directory is shown at the top of the Console pane, and you can check it with
getwd(). This is where R is ‘situated’ when loading or saving files. - Create a new .R file for that week’s practical.
To create a new .R file, click New Blank File at the top of the Files panel and selecting R Script. Name it Practical_1.R or similar.
RStudio Settings
You can adjust many settings in RStudio via Tools > Global options. In the Appearance tab in the popup box, you can set the theme (e.g., if you prefer a dark theme), font size, etc. The Code tab has many nice features as well (e.g., rainbow parentheses under Display).
R packages and libraries
R packages are collections of functions, custom data structures, and datasets that are developed by the user base. A new installation of R includes many useful packages, visible on the ‘Packages’ tab in RStudio. There are many additional packages available from the official CRAN repository or less officially from GitHub. If you find yourself re-using custom functions across projects, you can even create your own personal package.
To install a package from CRAN, use the function install.packages("packageName"). This downloads the package files to your computer. Each time you open R, you will need to load that package to use it with library(packageName).
Install the following packages which we will use this semester:
Installing from other package sources is slightly more complicated, so see me if you have a need.
View an overview of a package with ?packageName, and then see a list of all of the functions by scrolling to the bottom of the help page and clicking the “index” link.
The help for each function is available with ?functionName, and you can see the underlying code by running functionName without parentheses.
R scripts (.R) vs Quarto documents (.qmd)
In H1, you used R scripts (.R). These are just text files. The extension tells your computer to associate them with R, and also lets you run lines of code with ‘ctrl + enter’ and other convenient things in R and RStudio.
Quarto documents (.qmd) are also text files. However, RStudio interprets the text differently, allowing you to intersperse written prose, figures, references, R code, and output in a single document (similar to a jupyter notebook or a live script in Matlab). Code is marked as “chunks” and you can specify options for how the code and output are displayed. The text uses markdown formatting, which allows all sorts of formatting (headers, bold, italic, equations, hyperlinks, tables, images…). RStudio can render a .qmd file into many other formats (e.g., pdf, docx, html, epub…).
Code chunks can be added with the green button with a ‘(+)c’ on the top right of a .qmd document in RStudio. Code chunks look like this:
```{r}
# This is a code chunk
a <- 1:3
a
```[1] 1 2 3
Run the full block with the green ‘play’ button at the top right of the block. The output from the code is shown just below the block.
For code-heavy work, Quarto documents are a handy way to produce nicely formatted output without the hassle of copying and pasting code, output, and figures into, e.g., a word document. There are many guides and tutorials online.
This manual is written as a Quarto book. You are welcome to use either .R or .qmd files during the practicals.
Note that the project will be submitted as a .qmd file with a version rendered to .html, and the problem sets should be submitted as .html rendered from the .qmd files linked at the top of each problem set.
Writing R code
R has established best practices to make your meaning clear. Just like any language, you|can|write|with|your|own|system, but it’s easier for everyone to use standard conventions. See the full style guide for more.
A few key points:
- Use
<-to assign a value to an object. You may see=, which works, but is not preferred. - Use
#to write a comment which R will ignore. - Use spaces to make your code legible:
a <- c(1, 2, 3). - Avoid spaces in column names or file names as these are a pain to work with.
- Use names for objects that are short, but descriptive.
- Limit the length of a line of code to about 80 characters.
- Usually, variables should be nouns and functions should be verbs.
- Run the line of code where your cursor is (or everything you’ve selected) with ctrl + enter