1 Introduction
Intended Learning Outcomes
Functions used
- built-in (you can always use these without loading any packages)
- base::
.rs.restartR(),as.Date(),library(),paste(),sample(),Sys.Date() - utils::
?,install.packages(),vignette()
- base::
- other (you need to load each package to use these)
- beepr::
beepr::beep() - devtools::
devtools::install_github()
- beepr::
Setup
Download the RStudio IDE Cheatsheet
1.1 Installing R and RStudio
R is a programming language that you will write code in and RStudio is a program that makes working in R easier.
Install R and RStudio on your computer. We have written a guide for how to do this on Windows and Mac and also how to use RStudio on a UofG desktop computer.
Once you have installed R and RStudio, come back to this chapter. If you already had R and/or RStudio installed, we recommend updating to the latest version before you work through this course - there is also a guide for how to do this.
1.1.1 RStudio
When you installed R, that gave your computer the ability to process the R programming language, and also installed an app called “R”. We will never use that app. Instead, we will use RStudio.
Launch
, not
.
RStudio is an Integrated Development Environment (IDE). Think of it as using a plain text editor like NotePad to write a book versus using a word processor like Microsoft Word. You could do it, but it would be much harder without things like spell-checking and formatting and you wouldn’t be able to use some of the advanced features that Word has developed. In a similar way, you can use R without R Studio but we wouldn’t recommend it. (You can use your favourite IDE, but the examples in this book will all be shown in RStudio.) RStudio serves as a text editor, file manager, spreadsheet viewer, and more. The key thing to remember is that although you will do all of your work using RStudio for this course, you are actually using two pieces of software, which means that from time to time, both of them may have separate updates.
RStudio is arranged with four window panes.
By default, the upper left pane is the source pane, where you view, write, and edit code from files and view data tables in a spreadsheet format. When you first open RStudio, this pane won’t display until we open a document or load in some data – don’t worry, we’ll get to that soon.
The lower left pane is the console pane, where you can type in commands and view output messages. You can write code in the console to test it out. The code will run and can create objects in the environment, but the code itself won’t be saved. You need to write your code into a script in the source pane to save it, which we’ll cover in Chapter 2.
The right panes have several different tabs that show you information about your code. The most used tab in the upper right pane is the Environment tab, which lists some information about the objects that you have defined in your code.
In the lower right pane, the most used tabs are the Files tab for directory structure, the Plots tab for plots made in a script, the Packages tab for managing add-on packages (see Section 1.4), the Viewer tab to display reports created by your scripts, and the Help tab to see function help. We’ll learn more about the Help tab in Section 1.4.5.
You can change the location of panes and what tabs are shown in each pane under
1.1.2 Reproducibility
In this class, you will be learning how to make reproducible reports. This involves writing scripts that transform data, create summaries and visualisations, and embed them in a report in a way that always gives you the same results.

When you do things reproducibly, others (and future you) can understand and check your work. You can also reuse your work more easily. For example, if you need to create a report every month with the social media analytics for your company, a reproducible report allows you to download a new month’s data and create the report within seconds. It might take a little longer to set up the report in the first instance with reproducible methods, but the time it saves you in the long run is invaluable.
1.2 RStudio Settings
There are a few settings you should fix immediately after updating RStudio. , uncheck the box that says
Go to
- In the General tab, uncheck the box that says Restore .RData into workspace at startup.
- Change “Save workspace to .RData on exit” to “Never”.
You will need to change these settings each time you update RStudio.
1.2.1 Themes and accessiblilty
You can customise how RStudio looks to make it work for you. You can change the default font, font size, and general appearance of RStudio, including using dark mode.
Click
1.3 Sessions
If you have the above settings configured correctly, when you open up RStudio and start writing code, loading packages, and creating objects, you will be doing so in a new session and your Environment tab should be completely empty. If you find that your code isn’t working and you can’t figure out why, it might be worth restarting your R session. This will clear the environment and detach all loaded packages - think of it like restarting your phone. There are several ways that you can restart R:
- Menu:
Session > Restart R -
Cmd-Shift-F10 orCtl-Shift-F10 - type
.rs.restartR()in the console
Try each method of restarting R. Additionally, now would be a good time to start your reflective log where you can keep a record of useful hints and tips and things to try when your code isn’t working. Add “restart R session” to this notebook as your first item.
1.4 Packages and functions
When you install R you will have access to a range of functions including options for data wrangling and statistical analysis. The functions that are included in the default installation are typically referred to as base R and you can think of them like the default apps that come pre-loaded on your phone.
One of the great things about R, however, is that it is user extensible: anyone can create a new add-on that extends its functionality. There are currently thousands of packages that R users have created to solve many different kinds of problems, or just simply to have fun. For example, there are packages for data visualisation, machine learning, interactive dashboards, web scraping, and playing games such as Sudoku.
Add-on packages are not distributed with base R, but have to be downloaded and installed from an archive, in the same way that you would, for instance, download and install PokemonGo on your smartphone. The main repository where packages reside is called CRAN, the Comprehensive R Archive Network.
There is an important distinction between installing a package and loading a package.
1.4.1 Installing a package

This is done using install.packages(). This is like installing an app on your phone: you only have to do it once and the app will remain installed until you remove it. For instance, if you want to use PokemonGo on your phone, you install it once from the App Store or Play Store; you don’t have to re-install it each time you want to use it. Once you launch the app, it will run in the background until you close it or restart your phone. Likewise, when you install a package, the package will be available (but not loaded) every time you open up R.
Install the
If you get a message that says something like package ‘tidyverse’ successfully unpacked and MD5 sums checked, the installation was successful. If you get an error and the package wasn’t installed, Google the error message or use AI to help identify the problem.
Never install a package from inside a script. Only do this from the console pane or the packages tab of the lower right pane. This is because if you put the install code in a script, you might run it accidentaly and reinstall the package which will update it. Sometimes you want to do this, and sometimes a package update might cause your code to stop working.
Here are some other packages you’ll want to install for the first two chapters.
Once you’ve installed the
1.4.2 Loading a package
This is done using the library() function. This is like launching an app on your phone: the functionality is only there where the app is launched and remains there until you close the app or restart. For example, when you run library(devtools) within a session, the functions in the package referred to by devtools will be made available for your R session. The next time you start R, you will need to run library(devtools) again if you want to access that package.
You might get some red text when you load a package, this is normal. It is usually warning you that this package has functions that have the same name as other packages you’ve already loaded.
You can use the convention package::function() to indicate in which add-on package a function resides. For instance, if you see readr::read_csv(), that refers to the function read_csv() in the library(), you don’t have to specify the package name before a function unless there is a conflict (e.g., you have two packages loaded that have a function with the same name).
1.4.3 Using a function
A function is a name that refers to some code you can reuse. We’ll start by using functions that are provided for you in packages, but you can also write your own functions. After the function name, there is a pair of parentheses, which contain zero or more arguments. These are options that you can set. In the example above, the sound argument has a default value of 1, which makes a “ping” sound.
If you type a function into the console pane, it will run as soon as you hit enter. If you put the function in a script or Quarto document in the source pane, it won’t run until you run the script, knit the Quarto file, or run a code chunk. You’ll learn more about this in Chapter 2.
1.4.4 Tidyverse
-
ggplot2 , for data visualisation (Chapter 3) -
readr , for data import (Appendix C) -
tibble , for tables (Appendix C) -
tidyr , for data tidying (Chapter 8) -
dplyr , for data manipulation (Chapter 9) -
stringr , for strings (Appendix D) -
forcats , for factors (Section D.1.4) -
lubridate , for working with dates (Appendix E) -
purrr , for repeating things
When you install tidyverse_packages(), but the packages we’ll be using in this book are:
-
googlesheets4 , for working with Google spreadsheets -
readxl , for Excel files -
hms , for working with times -
rvest , for web scraping
1.4.5 Function Help
When you load the ?function_name in the console to access the help file. At the top of the help it will give you the function and package name.
If the package isn’t loaded, use ?package_name::function_name or specify the package in the help() function. When you aren’t sure what package the function is in, use the shortcut ??function_name.
Use the methods above to get help for the beepr::beep() function.
Function help is always organised in the same way. For example, look at the help for ?beepr::beep. At the top, it tells you the name of the function and its package in curly brackets, then a short description of the function, followed by a longer description. The Usage section shows the function with all of its arguments. If any of those arguments have default values, they will be shown like function(arg = default). The Arguments section lists each argument with an explanation. There may be a Details section after this with even more detail about the functions. The Examples section is last, and shows examples that you can run in your console window to see how the function works.
Use function help to answer the following questions.
- What is the first argument to the
meanfunction? - What package is
read_excelin?
1.5 Code Basics
1.5.1 Arguments
You can look up the arguments/options that a function has by using the help documentation. Some arguments are required, and some are optional. Optional arguments will often use a default (normally specified in the help documentation) if you do not enter any value.
As an example, look at the help documentation for the function sample() which randomly samples items from a list.
The help documentation for sample() should appear in the bottom right help panel. In the usage section, we see that sample() takes the following form:
In the arguments section, there are explanations for each of the arguments:
-
xis the list of items we want to choose from, -
sizeis the number of items we want to choose, -
replaceis whether or not each item may be selected more than once, -
probgives the probability that each item is chosen.
In the details section it notes that if no values are entered for replace or prob it will use defaults of FALSE (each item can only be chosen once) and NULL (all items will have equal probability of being chosen). Because there is no default value for x or size, they must be specified otherwise the code won’t run.
Let’s try an example and just change the required arguments x and size to ask R to choose from the set of letters (a built-in vector of the 26 lower-case Latin letters), 5 random values.
sample() generates a random sample. Each time you run the code, you’ll generate a different set of random letters (try it). The function set.seed() controls the random number generator - if you’re using any functions that use randomness (such as sample()), running set.seed() will ensure that you get the same result (in many cases this may not be what you want to do). To get the same numbers we do, run set.seed(1242016) in the console, and then run sample(x = letters, size = 5) again.
This time R has still produced 5 random letters, but now this set of letters has two instances of “k”. Always remember to use the help documentation to help you understand what arguments a function requires.
1.5.2 Argument names
In the above examples, we have written out the argument names in our code (i.e., x, size, replace), however, this is not strictly necessary. The following two lines of code would both produce the same result (although each time you run sample() it will produce a slightly different result, because it’s random, but they would still work the same):
Importantly, if you do not write out the argument names, R will use the default order of arguments. That is, for sample it will assume that the first value you enter is x, the second value is size and the third value is replace.
If you write out the argument names, then you can write the arguments in whatever order you like:
When you are first learning R, you may find it useful to write out the argument names as it can help you remember and understand what each part of the function is doing. However, as your skills progress you may find it quicker to omit the argument names and you will also see code examples online that do not use argument names, so it is important to be able to understand which argument each bit of code is referring to (or look up the help documentation to check).
In this course, we will always write out the argument names the first time we use each function. However, in subsequent uses they may be omitted.
1.5.3 Tab auto-complete
One very useful feature of R Studio is tab auto-complete for functions. If you write the name of the function and then press the tab key, RStudio will show you the arguments that function takes along with a brief description. If you press enter on the argument name it will fill in the name for you, just like auto-complete on your phone. This is incredibly useful when you are first learning R and you should remember to use this feature frequently.
Use tab autocomplete to figure out the arguments to rnorm(). Create a vector of 20 numbers from a normal distribution with a mean of 100 and a standard deviation of 10.
1.6 Scripts
The main purpose of this course is to teach you how to make fully reproducible reports where your text and code are all in one document. We will start using a document type called Quarto for this purpose next week but for now, we’ll just use a simple script which allows us to save our code.
There are several ways to create a new script:
- Click File - New File - R Script
- Click the New File icon, then click R Script
- Use the shortcut Ctrl/Cmd + Shift + N
Once you’ve created your new script, hit Ctrl/Cmd + S to save it. Name it ads-week1-1.R and save it somewhere sensible (on a cloud drive)
Scripts are useful for when you need to save the code you’re writing but you’re not bothered about making a full report. By default, everything you write in a script will be treat as code If you want to add any text as notes, you must use a comments. You can add comments inside scripts with the hash symbol (#). R will ignore characters from the hash to the end of the line.
In your script, copy and paste the following code and comments:
[1] "f" "m" "k" "i" "n"
To run the code in your script, use the keyboard shortcut Ctrl/Cmd + Enter on the line you want to run.
1.7 Objects
A large part of your coding will involve creating and manipulating objects. Objects contain stuff. That stuff can be numbers, words, or the result of operations and analyses. You assign content to an object using <- or = (we will use <- in this book).
You’ll see that four objects now appear in the environment pane:
-
nameis character (text) data. In order for R to recognise it as text, it must be enclosed in double quotation marks" ". -
ageis numeric data. In order for R to recognise this as a number, it must not be enclosed in quotation marks. -
todaystores the result of the functionSys.Date(). This function returns your computer system’s date. Unlikenameandage, which are hard-coded (i.e., they will always return the values you enter), the contents of the objecttodaywill change dynamically with the date. That is, if you run that function tomorrow, it will update the date to tomorrow’s date. -
halloweenis also a date but it’s hard-coded as a specific date. It’s wrapped within theas.Date()function that tells R to interpret the character string you provide as a date rather than text.
To print the contents of an object, type the object’s name in the console and press enter. Try printing all four objects now.
Finally, a key concept to understand is that objects can interact and you can save the results of those interactions in new object.
1.8 Getting help
You will feel like you need a lot of help when you’re starting to learn. This won’t really go away; it’s impossible to memorise everything. The goal is to learn enough about the structure of R that you can look things up quickly. This is why we’ll introduce specialised jargon in the glossary for each chapter; it’s easier to google “convert character to numeric in R” than “make numbers in quotes be actual numbers not words”. In addition to the function help described above, here’s some additional resources you should use often.
1.8.1 Package reference manuals
Start up help in a browser by entering help.start() in the console. Click on
1.8.2 Googling
If the function help doesn’t help, or you’re not even sure what function you need, try Googling your question. It will take some practice to be able to use the right jargon in your search terms to get what you want. It helps to put “R” or “tidyverse” in the search text, or the name of the relevant package, like “ggplot2”.
1.8.3 AI
Generative AI platforms have exploded in popularity, particularly when it comes to coding. Because of this, we have created a companion book AITutoR to show you how to use AI responsibly to support your coding journey.

While generative AI can be a very helpful tool to support coding, we ask you not to rely on it too heavily while you are building the essential skills for coding. The exercises are meant to build your mental models for understanding data. If you don’t have a good understanding of how data is structured, you cannot evaluate if AI suggestions are correct, contain subtle errors, or are wildly off base.
Coming back to the exercise analogy, while a forklift can lift heavy weights easier and faster than you can, it doesn’t help your sporting performance if you get a forklift to lift weights at the gym for you. The same is true for AI and coding. The exercises we ask you to do are relatively simple for AI to solve, but it’s important for you to be able to fluently solve them so that you have the necessary “fitness” to do more complex tasks.
1.8.4 Vignettes
Many packages, especially tidyverse ones, have helpful websites with vignettes explaining how to use their functions. Some of the vignettes are also available inside R. You can access them from a package’s help page or with the vignette() function.
1.9 Glossary
The glossary at the end of each chapter defines common jargon you might encounter while learning R. This specialised vocabulary can help you to communicate more efficiently and to search for solutions to problems. The terms below link to our PsyTeachR glossary, which contains further information and examples.
1.10 Peer Coding Exercises
If you’re enrolled on PSYCH1012 Applied Data Skills, do not do these exercises until the Tuesday workshop.
For each exercise, you’ll work in a pair programming team. Pair programming is when two people work on the same code with distinct, rotating roles:
The Driver operates the keyboard, implements the next small step, narrates what they are doing.
The Navigator reviews in real time, thinks ahead, checks naming, design, and help pages, and catches mistakes and typos.
You should work in short cycles (5-10 minutes or two or three tasks), then switch roles. You will likely feel a bit awkward doing this to begin with but you will quickly get used to it (we’re going to to it every week).
There are no solutions provided for the pair programming activities. Everything you need is in this chapter of the book so use the search function and work together to solve any problems.
- Decide who is going to start as the Driver and Navigator. Remember to switch every so often! The Navigator will find it helpful to have a copy of these instructions open and read the next step to the Driver.
- Open RStudio, ensure the environment is clear, and restart R.
- Increase the editor font size to 14.
- Open a new script and save it with the name
ads-week1-2.R - Create a character object called
namewith the current Driver’s name, an object calledtodaythat pulls the date from the computer system, an object calledads_reportthat contains the deadline of the final report for Applied Data Skills. - Subtract today’s date from your target date and store it as a new object called
days_left. - Use
paste()to combine your name and the number of days into a single sentence - add this to your script.
- Print the message. How many days are there until the final report is due? (this answer will only be correct if you complete this exercise on the 13th January).
- Add in comments with any problems you encountered along the way, or anything you learned.
- Use
beep()to play the Mario sound. - Save the file and make sure you both have a copy (send it to the other person via Teams or OneDrive)
| term | definition |
|---|---|
| argument | A variable that provides input to a function. |
| base-r | The set of R functions that come with a basic installation of R, before you add external packages. |
| character | A data type representing strings of text. |
| chunk | A section of code in an R Markdown file |
| comment | Comments are text that R will not run as code. You can annotate .R files or chunks in R Markdown files with comments by prefacing each line of the comment with one or more hash symbols (#). |
| conflict | Having two packages loaded that have a function with the same name. |
| cran | The Comprehensive R Archive Network: a network of ftp and web servers around the world that store identical, up-to-date, versions of code and documentation for R. |
| data-wrangling | The process of preparing data for visualisation and statistical analysis. |
| default-value | A value that a function uses for an argument if it is skipped. |
| factor | A data type where a specific set of values are stored with labels; An explanatory variable manipulated by the experimenter |
| function | A named section of code that can be reused. |
| ide | Integrated Development Environment: a program that serves as a text editor, file manager, and provides functions to help you read and write code. RStudio is an IDE for R. |
| knit | To create an HTML, PDF, or Word document from an R Markdown (Rmd) document |
| numeric | A data type representing a real decimal number or integer. |
| object | A word that identifies and stores the value of some data for later use. |
| package | A group of R functions. |
| panes | RStudio is arranged with four window “panes”. |
| quarto | An open-source scientific and technical publishing system. |
| script | A plain-text file that contains commands in a coding language, such as R. |
| string | A piece of text inside of quotes. |
| vector | A type of data structure that collects values with the same data type, like T/F values, numbers, or strings. |