n_items <- 20Data Skills for Psychology — Module 2
These slides are adapted from R for Psychological Science by Danielle Navarro.
By the end of this class, you will be able to:
These five concepts — variables, vectors, loops, branches, and functions — are the building blocks of every programming language.
Once you understand them in R, you’ll recognize them everywhere: Python, JavaScript, even Excel formulas use the same ideas.
Today we’re learning to “speak the computer’s language.”
A variable is a label for a piece of information. Think of it as a named container.
Since n_items holds a number, we can use it in calculations:
Try it!
Imagine you’re designing a survey. Create variables for:
Print the total time. Then add 60 seconds for instructions and update your total.
Text data must be enclosed in quotes — single or double:
Logical values arise from tests — asking R true-or-false questions:
The == is the equality operator. Don’t confuse it with = (assignment)!
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to | 5 == 5 |
TRUE |
!= |
not equal to | 5 != 3 |
TRUE |
< |
less than | 3 < 5 |
TRUE |
<= |
less than or equal | 5 <= 5 |
TRUE |
> |
greater than | 3 > 5 |
FALSE |
>= |
greater than or equal | 5 >= 3 |
TRUE |
Try this
You ran an online experiment. You want to keep data only from participants who were actively paying attention during your experiment. Write some code to help you find who to exclude.
Create a variable use_data that is FALSE if they failed either attention check.
Rules R enforces:
. and _ (no spaces!)Survey ≠ surveyif, TRUE, for, etc.)Good conventions:
n_items not xn_items not number_of_survey_itemssnake_case)R has four special values you’ll encounter:
| Value | Meaning | Example |
|---|---|---|
Inf |
Infinity | 1 / 0 |
NaN |
Not a Number | 0 / 0 |
NA |
Missing data | Data lost or not recorded |
NULL |
No value at all | Variable doesn’t exist |
NA is the one you’ll see most often in real data analysis — it means the data is missing.
A vector is a variable that stores multiple values. Create one with c() (combine):
Use square brackets [] with an index number:
Change a single element by assigning to its index:
R applies operations to every element at once:
This is one of the most powerful ideas in R. You can use a logical vector to filter another vector:
Try these
age with four ages: 19, 34, 7, 67gender for those four peopleadult using >=A loop repeats a block of code over and over until a condition is met.
Without a loop:
do step 1 → do step 2 → do step 3 → done
With a loop:
do step 1 → check: keep going? → yes → do step 1 again → check...
Two types: while loops and for loops.
while LoopA while loop keeps going as long as a condition is TRUE:
while Loopfor LoopA for loop runs a fixed number of times, once for each element in a vector:
for Loops Over Character VectorsLoops aren’t just for numbers! You can loop over any vector:
What will this produce?
while vs. for: When to Use Which?for loopwhile loopA conditional statement lets your code make decisions: do different things depending on whether a condition is true or false.
The condition must produce a single TRUE or FALSE value.
if and elseelse ifYou can chain multiple conditions together:
R checks each condition in order. As soon as one is TRUE, it runs that block and skips the rest.
The real power comes from combining these ideas:
Try it!
Write an if/else statement that prints “Pass” if a variable score is 60 or above, and “Fail” otherwise. Test it with different values.
Extend it with else if to print “A” for 90+, “B” for 80+, “C” for 70+, “D” for 60+, and “F” below 60.
Challenge: Put it inside a for loop that grades a whole vector of scores:
We’ve been using functions all along (print(), nchar(), c()…). Now let’s write our own.
FNAME is the name you give your functionARG1, ARG2 are the inputs (arguments)return() sends the result back to the callerNote
The variables x and y exist only inside the function — they don’t appear in your environment. This is called local scope.
You can give arguments default values:
If an argument has no default and you don’t provide it, R will throw an error.
Try these
Write a function round_sqrt that takes a number x, computes the square root, rounds it to the nearest whole number, and returns the result.
Add a digits argument so the user can control how many decimal places to round to. Give it a default value of 0.
Test it: round_sqrt(17) should return 4. round_sqrt(17, digits = 2) should return 4.12.
Functions become extremely powerful when combined with loops and branches. Consider this:
Combine everything you’ve learned!
Write a function fizzbuzz that takes a number n and:
n is divisible by 3n is divisible by 5Then use a for loop to run fizzbuzz on the numbers 1 through 20.
Hint: the modulo operator %% gives the remainder. So n %% 3 == 0 checks divisibility by 3.
| Concept | What it does | Key syntax |
|---|---|---|
| Variables | Store a single value | x <- 10 |
| Vectors | Store multiple values | c(1, 2, 3) |
| Loops | Repeat code | for (i in 1:10) { } |
| Branches | Make decisions | if (x > 0) { } else { } |
| Functions | Reusable code blocks | f <- function(x) { } |
These five ideas combine to let you automate almost anything!
📖 Read: The chapters on Variables, Vectors, Loops, and Branches from R for Psychological Science
✍️ Assignment: Complete the exercises from each chapter, plus the additional problems on the module page
🧠 Remember: These are foundational skills — practice makes them second nature!
❓ Questions?