flowchart LR
A["Raw data"] --> B["Many clicks"] --> C["A number in the thesis"]
D["An examiner asks: how?"] -.-> B
Getting Started with R
Getting Started with R
Research written in code
Chapter 1
Polla Fattah
By the end of today you can
- explain why researchers write their analysis in R;
- find your way around RStudio;
- run code in the Console and in a script;
- store values in objects and recognise the basic types of data;
- handle missing values;
- use functions and their arguments, and get help;
- organise work in an RStudio Project and install packages;
- open the student wellbeing data and answer a first question.
Every analysis is a chain of decisions
- which cases are kept and which are excluded;
- how a messy answer is corrected;
- which variables are combined into a score;
- which test is used;
- how the result is rounded.
Each choice shapes the final numbers, and each should be open to inspection.
Point-and-click leaves no trace
Weeks later, not even the researcher can say exactly how the number was produced.
Code is a record of the analysis
A script records every step, in order.
- a supervisor can read it;
- an examiner can check it;
- the researcher can run it again after fixing a mistake or receiving new data.
An analysis written as code can be shown step by step.
What R is
R is a free program for cleaning, analysing, and presenting data.
It began in the early 1990s at the University of Auckland, written by Ross Ihaka and Robert Gentleman for teaching.
Today it is used in universities, hospitals, governments, and companies around the world.
Four reasons researchers use R
| Property | Why it matters |
|---|---|
| made for data | tests, models, and graphs are part of the language |
| free and open source | anyone can check your work without a licence |
| reproducible | the same code gives exactly the same results |
| a large community | thousands of free packages for every field |
The price: you type instead of click. It feels slow at first and fast surprisingly soon.
For users of SPSS or Excel
SPSS / Excel: click → the program changes the data
R: write → R carries out the instruction
The instructions are saved in a file.
Next time, you run the file instead of clicking through the menus again.
The study behind the data
A two-year study of 600 graduate students from five faculties:
- a questionnaire at the start;
- sleep, study, and wellbeing recorded at the end of every semester;
- a six-week wellbeing workshop, with half the students invited at random.
The questions: how do sleep, stress, and supervisor support relate to wellbeing, grades, and thoughts of dropping out, and does the workshop help?
The data is fictional
The student wellbeing data was generated by a computer program to look like a realistic survey.
Its patterns were built in by the author, not discovered.
It describes no real people. Do not cite or use it as findings about real students.
Two programs: R and RStudio
flowchart LR
A["You write code<br>in RStudio"] --> B["R does the work"] --> C["Results appear<br>in RStudio"]
R is the engine. RStudio is where you drive it.
You almost never open R itself.
Installing both
- Install R from cran.r-project.org for your operating system.
- Install RStudio Desktop from posit.co.
R must be installed first. Appendix A walks through both, with solutions to common problems.
Positron, a newer editor from the same company, is a good alternative if you also use Python.
The four panes of RStudio
| Where | Pane | What it is for |
|---|---|---|
| top left | Source | writing and saving scripts |
| bottom left | Console | running code and showing results |
| top right | Environment | the objects you have created |
| bottom right | Files, Plots, Packages, Help | files, graphs, packages, help pages |
The Console answers straight away
Type in the Console and press Enter.
[1] means “this is the first value of the result”. Ignore it for now.
R as a calculator
Three nights of sleep, averaged.
The symbols: +, -, * (multiply), / (divide), ^ (power).
Brackets decide the order
Without brackets, R divides only the last number by 3.
Multiplication and division come before addition and subtraction; brackets come first of all.
Store a value under a name
The stored value is an object. The assignment arrow <- reads as “gets”.
Nothing is printed on assignment, but the object appears in the Environment pane.
Several values in one object
c() stands for combine. The result is a vector (Chapter 2).
Named values make code clearer than bare numbers.
Rules for names
| Rule | Good | Not allowed or unwise |
|---|---|---|
| start with a letter | sleep_week1 |
1week |
| no spaces | sleep_hours |
sleep hours |
| case matters | sleep ≠ Sleep |
mixing both by accident |
| say what it holds | sleep_hours |
x |
Your future self will be grateful for clear names.
Reassignment replaces silently
The old value is gone, without a warning.
Check the Environment pane when a result surprises you.
Every value has a type
| Type | Holds | Example |
|---|---|---|
| numeric | numbers | 6.5, 600 |
| character | text in quotes | "Education" |
| logical | yes or no | TRUE, FALSE |
The type decides what can be done: hours of sleep can be averaged, faculty names cannot.
class() reports the type
Text needs quotes
Without quotes, R looks for an object called Education.
One of the most common beginner errors, and the message says exactly what went wrong.
NA marks a missing value
NA means not available: not zero, not empty text, but “we do not know”.
If one value is unknown, the average is unknown too. R does not guess.
Functions take input and return a result
A function name is followed by brackets, with the input inside.
You have already used c(), sum(), mean(), and class().
Arguments are the inputs
Arguments are separated by commas, and they have names.
round(6.333333, 1) gives the same result, but the named version is easier to read.
na.rm leaves missing values out
na.rm is short for “NA remove”.
The average of the values R does know.
Functions inside functions
R works from the inside out: first the mean, then the rounding.
Getting help
The help page opens in the Help pane. Start with three parts:
- Usage: how to call the function;
- Arguments: what each input means;
- Examples: code you can copy and run.
Treat suggested code with care
Code from a search engine or an AI assistant is like advice from a knowledgeable stranger.
Often right, sometimes wrong, always worth checking.
Chapter 18 shows how to use AI tools well.
Console code disappears
Code typed in the Console is gone when RStudio closes.
A script is a plain text file, ending in .R, that holds your instructions in order.
File > New File > R Script opens one in the Source pane.
Working in a script
| Action | Windows | Mac |
|---|---|---|
| run the line or selection | Ctrl+Enter | Cmd+Enter |
| save the script | Ctrl+S | Cmd+S |
The code is sent to the Console, and the result appears there.
An RStudio Project keeps one piece of work together
wellbeing-thesis/
├── wellbeing-thesis.Rproj
├── data/
├── figures/
└── analysis.R
File > New Project > New Directory > New Project.
Open the project by double-clicking the .Rproj file.
The working directory
The folder R looks in for files is the working directory.
In a project, it is the project folder:
A file stored there opens by its name alone.
here() builds paths from the project folder
The same code works on any computer, and in any subfolder.
Avoid setwd()
That line works only on the computer where it was written.
Use a project, and your code works for your supervisor too.
Packages add new abilities
Install downloads the package from CRAN, R’s official collection.
Load makes it available in the current session.
Installing is buying, loading is reading
flowchart LR
A["install.packages()<br>buy the book once"] --> B["On your shelf"]
B --> C["library()<br>take it down each session"]
Forgetting library() is the usual cause of “could not find function”.
The data package: data2thesis
install.packages(
"https://polla-fattah.github.io/data2thesis_r/downloads/data2thesis_1.1.0.tar.gz",
repos = NULL, type = "source")
library(data2thesis)It is not on CRAN, so it is installed from the book’s website.
Data frames: one row per case
The package holds several data frames: tables with one row per case and one column per variable.
The main one is students, one row per student.
Looking at the data
head(students) # the first six rows
names(students) # the variable names
?students # what each variable meansLook before you analyse: what is in each column, and what does one row represent?
$ picks out one variable
The data frame’s name, a dollar sign, the variable’s name.
The result is a vector of every student’s age.
A first question: how old are the students?
One age is missing, and R will not guess.
The solution is already familiar.
Leaving the missing age out
The students are 29.7 years old on average.
Counting missing values
is.na() marks each missing value as TRUE.
sum() counts them, because R counts every TRUE as 1. Chapter 3 shows why the age is missing.
table() counts categories
Five faculties, from 87 to 154 students each.
Exactly 300 students were invited to the workshop: half, chosen at random (Chapter 5).
In your field: agriculture
Dried plant weight under a control and two treatments, 10 plants each.
The same functions work on any data frame. data() lists R’s built-in datasets.
Practical lab: the Chapter 1 playground
Work through the playground exercises in your browser, with hints and solutions.
Every exercise also runs in RStudio, from the downloadable chapter project.
Practical exercises 1–3: objects and types
- Store a supervisor’s four nights of sleep and find the rounded average.
- Compare
class("600")andclass(600), and explain the difference. - Explain why
mean(c(4, NA, 6))returnsNA, then average the known values.
Practical exercises 4–6: the data
- Find the youngest and the oldest student;
min()andmax()also takena.rm. - Count the part-time students with
table(). - List three decisions in a point-and-click analysis that a reader could not check.
Try this yourself
Create an RStudio Project for your own thesis.
- add
data/andfigures/folders; - write a script that loads data2thesis;
- count the students in each faculty;
- add a comment above each line explaining why.
Then close RStudio, reopen the project, and run the script again from the top.
Troubleshooting guide (Part 1)
| Symptom | Likely cause |
|---|---|
object 'Education' not found |
text written without quotes |
could not find function |
the package is not loaded with library() |
the result is NA |
a missing value; add na.rm = TRUE |
+ appears in the Console |
an unfinished line, often a missing bracket |
Troubleshooting guide (Part 2)
| Symptom | Likely cause |
|---|---|
| a file cannot be found | not working inside the project |
| code works only on your computer | setwd() with a personal path |
| a value changed unexpectedly | the name was reassigned silently |
| yesterday’s work is gone | code typed in the Console, not a script |
Completion checklist
Misconceptions to leave behind (Part 1)
| Misconception | Better mental model |
|---|---|
| R and RStudio are the same program | R is the engine; RStudio is where you drive it |
NA is the same as zero |
NA means “we do not know” |
| installing a package makes it available | it must also be loaded each session |
Misconceptions to leave behind (Part 2)
| Misconception | Better mental model |
|---|---|
| code is only for programmers | code is a written record of research decisions |
| the Console is where work is kept | scripts keep the work |
setwd() sets up a project |
a Project makes paths portable |
The chapter in one sentence
Write the analysis as code in a script inside a project, so every number in the thesis can be shown step by step.
Next: Chapter 2
The next chapter looks at data as measurement:
- levels of measurement and vectors;
- factors for categories;
- data frames, matrices, and lists;
- importing CSV, Excel, and SPSS files;
- codebooks, exporting, and reading error messages.
Questions
Think of one number in a thesis or paper you have read.
Could its author show you, step by step, how it was produced?
Comments explain why
Lines starting with
#are ignored by R. They are notes for people.When a supervisor asks how a number was obtained, the script is the answer.