Open instructor guide and worked solutions
Our original solution examples, expected numbers and teaching plan are publicly available. Students may prefer attempting the exercises before opening the answers.
Lesson 0 public solutions Instructor guide
Before memorising code, learn to formulate the question you want a computer to answer. We will start with a small psychology data problem and explore algorithms, objects, functions, conditions, repetition, missing values and debugging.
What is programming?
Programming is the process of turning a problem into sufficiently precise, testable instructions that a computer can execute. Writing code is only part of that process. A good programmer defines what needs to be measured, designs operations, investigates errors, tests results and interprets the output.
Four key distinctions
Problem
What do we want to know? For example, 'How did scores change among participants?'
Algorithm
An ordered plan: obtain data, identify missing values, calculate differences, check the result
R
The programming language we use to express our plan to a computer
RStudio
An environment for writing, running and exploring R code, not the R language itself
Six questions before writing code
- 1. What is the question? State it in one precise, measurable sentence.
- 2. What is the input? Define what each row and column means.
- 3. What is the output? Do you need a table, a number, a plot or a decision?
- 4. What is the sequence? Describe the steps in everyday language first.
- 5. What can go wrong? Missing values, incorrect labels, wrong paths?
- 6. How will you check it? Calculate by hand, test, then interpret.
Six building blocks of programming
1 · Values and types
12 is numeric; "A" is character data; TRUE/FALSE is logical. Different types support different operations.
2 · Variables / objects
`score <- 12` assigns the value 12 to the object called `score`. The left side is the name; the right side is the evaluated value.
3 · Vectors
`c(12, 10, 14)` stores several values together. R can apply many operations to a whole vector.
4 · Functions
`mean(scores)` calls a previously defined operation. `mean` names the task; `scores` is an input argument.
5 · Conditions and decisions
`scores >= 12` returns TRUE/FALSE for each value. A condition can determine which observations are selected.
6 · Repetition and checking
Applying the same rule consistently and checking with tools such as `is.na()` makes a program more reliable.
Your first working R program
Before running it, predict the number of valid observations and the average it will print.
scores <- c(12, 10, 14, NA, 9)
length(scores)
mean(scores)
mean(scores, na.rm = TRUE)
sum(!is.na(scores))
`NA` means missing or unknown, not zero. Explain why `mean(before)` returns NA and what `na.rm = TRUE` changes.
A tiny psychology data problem
These five records are invented for teaching; they are not genuine UCL research data. Compare each person's scores at two time points.
| Person | Before | After |
|---|
| A | 12 | 14 |
| B | 10 | 13 |
| C | 14 | 13 |
| D | NA | 15 |
| E | 9 | 12 |
Download the student starter file and work through the steps. Record your prediction before asking the computer for its result.
id <- c("A", "B", "C", "D", "E")
before <- c(12, 10, 14, NA, 9)
after <- c(14, 13, 13, 15, 12)
delta <- after - before
data.frame(id, before, after, delta)
mean(delta, na.rm = TRUE)
sum(delta > 0, na.rm = TRUE)
- By how many points did A change? Did C increase or decrease?
- Can D's change be calculated when the pretest score is missing?
- For how many people can you compute a change? How many increased?
- Why does the mean of all posttest scores answer a different question from the mean of paired individual changes?
Optional preview: decisions, repetition and your own functions
You do not need to master these before Week 1. First understand what the computer must do; later you can express reusable instructions with conditions, loops and functions.
if (sum(!is.na(scores)) > 0) {
average <- mean(scores, na.rm = TRUE)
} else {
average <- NA_real_
}
print(average)
for (number in c(2, 4, 6)) {
print(number)
}
double <- function(x) {
2 * x
}
double(c(1, 2, 3))
Predict: What happens if all scores are NA? What does the loop print? Can R double a whole vector without a loop?
R often uses vectorised operations instead of explicit loops. Both can express repeated work; use the clearest method for the task.
Original problem bank
Conceptual · Hands-on · Debugging
A1 · Describe an algorithm
Without coding, describe in 4–6 steps how to compute the mean of survey answers while excluding missing responses.
Show a hint
Specify the input, the missing-data rule and the output.
A2 · Predict the output
Predict the result of `x <- c(2, 4, 6)` followed by `mean(x)`; then run it.
Show a hint
R first assigns the object and then evaluates the function.
B1 · Count valid records
Find the number of non-missing pretest observations with `sum(!is.na(before))` and explain why.
Show a hint
`is.na()` identifies missingness; `!` negates a logical result.
B2 · Direction of change
Create `delta <- after - before`. How many scores increased or decreased? Handle missingness correctly.
Show a hint
Think about logical comparisons and the `na.rm` rule.
C1 · A missing mean
Why is `mean(before)` NA? What does `mean(before, na.rm=TRUE)` change? Does that solve the full research problem?
Show a hint
A working command is not necessarily a sound analytical decision.
C2 · An invalid conclusion
Suppose the mean posttest score is higher. Why might 'the intervention definitely worked' be unjustified?
Show a hint
Consider paired comparisons, attrition and causality.
Common beginner misconceptions
- `<-` assigns a value, whereas `==` tests whether two values are equal.
- `NA` denotes missing or unknown data; replacing it with 0 requires a defensible reason.
- `mean(x)` and `mean(x, na.rm=TRUE)` use different missing-data rules.
- A chart or successfully executed command does not prove that measurements or interpretations are valid.
- Always check a dataset's codebook before interpreting coded values such as 0/1 or 1/2.
Connections to your next four weeks
Week 1
Develop objects, functions, vectors and data frames.
Week 2
Learn CSV import, joins and filtering; audit coded labels.
Week 3
Break AQ-10 scoring into smaller transformations; test each join.
Week 4
Connect plot choice and interpretation limits to programming decisions.
Five-question exit ticket
- How is programming different from simply writing code?
- Are R and RStudio the same thing?
- What three elements should you specify before coding a problem?
- What should you check when a numerical vector contains NA?
- Why can a program run without errors yet still produce a misleading result?