← Home

For PSYC121 / Statistics for Psychologists / Lancaster University

RStudio, without the panic

RStudio looks like an aeroplane cockpit the first time you open it. It isn't. You write instructions, R carries them out, and the answer appears. That's the whole loop — everything else is detail.

Try it below: press Run line to send each instruction, and click any panel to see what it's for.

Week_2.Rpenelope22.csv 1library(tidyverse) 2cows <- read_csv("penelope22.csv") 3mean(cows$estimate) 4# the mean guess of the cow's weight
EnvironmentHistory Nothing here yet. Objects you create will appear in this list.
ConsoleTerminal >
FilesPlotsHelp week_1 week_2   Week_2.R   penelope22.csv

The highlighted line in the script is the one that will run next.

The big idea

R is the engine: a language that does maths, handles data and draws graphs. RStudio is the dashboard you drive it from. You never really "use R" on its own — you type R instructions into RStudio, and RStudio passes them to R.

Think of R as a very fast, very literal assistant. It does exactly what you write, in the order you write it, and nothing else. It can't guess what you meant. A missing comma, a capital letter in the wrong place or a file it can't see will stop it — and it tells you so with an error message. Errors are not you failing; they are R asking for clearer instructions.

You are not expected to memorise code

Nobody does. Every week the lab gives you a script that already contains most of what you need. Your real job is to read it, run it, and change small bits. Copying and adapting is exactly how professionals work too.

The four panels

RStudio splits the screen into four areas. Once you know which one does what, it stops feeling cluttered.

Script — top left

Your recipe. This is where you write and keep instructions. It's a file (ending in .R) that you save, so you can come back next week and repeat everything. If the file name shows in red with an asterisk, it has unsaved changes.

Console — bottom left

Where R actually runs things and shows the results. Each instruction appears after a > prompt with the answer underneath. Think of it as R talking back to you.

Environment — top right

R's memory. Every object you create (a dataset you've loaded, a number you've stored) is listed here. If something isn't in this list, R doesn't know about it — which explains a lot of errors.

Files, Plots and Help — bottom right

A file browser for your space on the server (this is where you upload the weekly zip), the place graphs appear, and the built-in help pages. Type ?mean in the console and the help for mean() opens here.

Script, not console

This one habit prevents more confusion than anything else on this page.

Write in the script

  • Saved — you keep a record of what you did
  • Easy to fix a typo and run it again
  • You can add notes with #
  • Next week, re-run the lot in seconds

Typing in the console

  • Gone once you close the session
  • Fine for a quick one-off check
  • Like scribbling on a sticky note

To run a line from the script, click anywhere on it and press CtrlCmd + Enter (or click the Run button at the top of the script panel). R runs that line and moves the cursor to the next one, so you can step through a script by pressing it repeatedly — just like the demo at the top of this page.

Run from top to bottom

Scripts depend on earlier lines. Line 2 loads the data that line 3 uses. If you jump straight to line 3, R says it can't find the object. When in doubt, go back to line 1 and run everything in order.

Your weekly routine

Every PSYC121 lab follows roughly the same pattern. Once this is automatic, you can spend your brainpower on the statistics instead.

  1. Get connected

    On campus, use Eduroam. Off campus, switch on the university VPN first — the server won't load without it.

  2. Log in to the RStudio server

    Go to psy-rstudio.lancaster.ac.uk, choose Sign in with SAML and use your normal university login. Everything lives on the server, so you'll see the same files from any computer.

  3. Make a folder for the week

    In the Files tab (bottom right), click New Folder, call it something like week_4, then click into it. One folder per week keeps things findable.

  4. Upload the zip

    Download the week's zip from the lab page, then in Files click Upload and choose it. The server unpacks it for you, so you'll see the script and data files appear.

    On a Mac, Safari sometimes unzips downloads automatically. If you end up with a folder instead of a .zip, either upload the files inside it one by one, or turn off "Open 'safe' files after downloading" in Safari's settings.

  5. Open the script and Save As

    Click the .R file to open it. Use File ▸ Save As to make your own copy (e.g. week_4_freya.R) so you keep an untouched original.

  6. Point R at the right folder

    Choose Session ▸ Set Working Directory ▸ To Source File Location. This tells R "look for data files in the same folder as this script". Skipping this is the number one cause of "file does not exist" errors.

  7. Load the tidyverse

    Run library(tidyverse) first, every session. It switches on the extra tools (read_csv, %>%, ggplot and friends). The wall of red-ish messages it prints is normal — it's not an error.

  8. Work through the script

    Run line by line, read what comes out, and add your own # notes saying what each bit does in your own words. Those notes are revision gold before the class tests.

  9. Save, then switch off

    Save the script (CtrlCmd + S), then click the red power button at the top right to end your session cleanly.

Reading R code

Almost every line you'll see in first year is built from the same handful of pieces. Learn to spot these and scripts start to read like sentences.

<-

"Store this under this name"

The arrow puts whatever's on the right into a named object on the left. The name is your choice — it then appears in the Environment panel.

cows <- read_csv("penelope22.csv")
name()

Functions do the work

A function is a verb. Its name comes first, then brackets containing what it should work on, plus any options separated by commas.

mean(cows$estimate, na.rm = TRUE)
$

"The column called…"

A dataset is a table. The dollar sign picks one column out of it: cows$estimate means "the estimate column of cows".

" "

Quotes mean "literally this text"

File names and bits of text go in quotes. Names of objects and columns don't. read_csv("cows") looks for a file called cows; mean(cows$estimate) uses the object.

#

Notes for humans

Anything after a hash is ignored by R. Use it to explain things to future you.

# average guess, ignoring missing answers
mean(cows$estimate, na.rm = TRUE)
%>%

"…and then…"

The pipe passes the result on the left into the next step. It lets you chain steps in reading order. (You may also see |>, which does the same job.)

= vs ==

Set versus check

A single = sets an option inside a function (na.rm = TRUE). A double == asks a question: "is this equal to that?" — you'll use it when filtering, e.g. filter(identity == "female").

Aa

Capitals matter

R is case-sensitive. Cows, cows and COWS are three different things. Spaces in names aren't allowed, which is why the course uses underscores: mean_estimate.

Pipes in plain English

Week 3 introduces chains like the one below. They look intimidating, but read top to bottom, saying "and then" at every %>%, they're just a list of instructions.

RWhat it's saying
cows %>%Take the cows data, and then…
group_by(identity) %>%…split it into groups by gender identity, and then…
summarise(mean_estimate = mean(estimate))…for each group, work out the mean estimate and call that column mean_estimate.

The result is a small table with one row per group. Swap mean for median or sd, or swap identity for another grouping column, and you've got a different analysis — that's what most lab exercises are really asking you to do.

Inside a pipe you don't need the cows$ part. Because the data has already been passed in, you can just write the column name.

A few more verbs you'll meet

# keep only some rows
cows %>% filter(estimate > 1000)

# add a new column calculated from another
cows %>% mutate(estimate_kg = estimate * 0.4536)

# count how many rows are in each group
cows %>% count(identity)

Graphs with ggplot

ggplot builds a graph in layers, like stacking transparent sheets. You always start with the data and say what goes on each axis, then add a layer that decides the shape.

cows %>%
  ggplot(aes(x = identity, y = estimate)) +   # the data and the axes
  geom_boxplot() +                            # draw boxplots
  labs(title = "Guesses of Penelope's weight",
       x = "Gender identity",
       y = "Estimate (lbs)")                  # tidy labels

aes() is short for "aesthetics" — which column maps to x, which to y, which to colour. Swap geom_boxplot() for geom_violin() or geom_jitter() and the same data gets drawn a different way. For a single column, try ggplot(aes(x = estimate)) + geom_histogram().

The one ggplot trap

Before ggplot() you use the pipe %>%. After it, layers are joined with +. Using %>% between layers is the classic mistake — R will even hint "did you use %>% instead of +?"

Error decoder

Red text in the console is R telling you what it couldn't do. These are the ones that catch almost everyone. Type a few words from your error to find it.

could not find function "read_csv" (or "%>%", "ggplot", "group_by"…)
Meaning
The tidyverse isn't switched on in this session.
Fix
Run library(tidyverse), then try again. You need to do this every time you start a new session.
object 'cows' not found
Meaning
R has nothing by that name in its memory (check the Environment panel).
Fix
Run the earlier line that creates it (usually the read_csv line). Also check spelling and capitals — Cows isn't cows.
'penelope22.csv' does not exist in current working directory
Meaning
R is looking in the wrong folder, or the file name doesn't match exactly.
Fix
Session ▸ Set Working Directory ▸ To Source File Location. Then check the name in the Files panel letter for letter, including .csv.
Error: unexpected symbol / unexpected ')' / unexpected string constant
Meaning
A typo in the shape of the code: a missing comma, an extra or missing bracket, or a quote that wasn't closed.
Fix
Look just before the spot R quotes. Click next to a bracket — RStudio highlights its partner, so you can see which one is missing.
The console shows + instead of >
Meaning
R thinks your instruction isn't finished yet (usually an unclosed bracket or quote) and is waiting for the rest.
Fix
Click in the console and press Esc to cancel. Fix the line in your script and run it again.
[1] NA
Meaning
Not strictly an error. Some values in that column are missing (NA), and any sum involving a missing value comes out missing.
Fix
Add na.rm = TRUE: mean(cows$female_estimate, na.rm = TRUE).
argument is not numeric or logical: returning NA
Meaning
You asked for a mean of something that isn't numbers — often because the column name after $ is misspelt, so R found nothing.
Fix
Run names(cows) to list the real column names and copy one exactly.
Did you use %>% or |> instead of +?
Meaning
A ggplot layer was joined with a pipe.
Fix
After ggplot(…), join every layer with + at the end of the line.
there is no package called 'something'
Meaning
That add-on isn't installed. On the university server the course packages are already there, so check the spelling first.
Fix
If you're using RStudio on your own laptop, install it once with install.packages("something").
Everything is weird and nothing works
Meaning
R's memory has got into a muddle, usually from running lines out of order.
Fix
Session ▸ Restart R, then run the script again from line 1. This fixes a surprising number of problems.

No match. Try fewer words — or copy the whole error into the Moodle forum along with your code.

Shortcuts worth learning

You can do everything with menus, but these few save a lot of clicking.

Run the current line (or highlighted lines)Ctrl + EnterCmd + Return
Run the whole scriptCtrl + Shift + EnterCmd + Shift + Return
Type the arrow <-Alt + -Option + -
Type the pipe %>%Ctrl + Shift + MCmd + Shift + M
Turn lines into comments (or back)Ctrl + Shift + CCmd + Shift + C
Save the scriptCtrl + SCmd + S
Finish a name for you (object, column or function)Tab
Bring back your last command (in the console)↑
Cancel a stuck command (in the console)Esc
Clear the consoleCtrl + L

Because RStudio runs in a web browser, a few shortcuts can be grabbed by the browser instead. If one doesn't work, use the menu or the Run button.

Cheat sheet

The functions that come up in PSYC121, grouped by what you're trying to do. The dashed box is for later in the term.

Getting data in

library(tidyverse)
Switch on the toolkit. First line, every session.
read_csv("file.csv")
Load a spreadsheet. Store it with <-.
c(7, 8, 3)
Make a short list of numbers by hand.

Looking at data

View(cows)
Open it like a spreadsheet. Capital V.
glimpse(cows)
Quick look at the columns and first values.
names(cows)
List the column names exactly.
summary(cows)
Min, max, mean and more for every column.

Describing

mean(x) / median(x)
Central tendency.
sd(x)
Standard deviation.
na.rm = TRUE
Add inside any of these to ignore missing values.

Groups and subsets

group_by(column)
Split into groups by an IV.
summarise(new = mean(col))
One summary row per group.
count(column)
How many in each category.
filter(column == "value")
Keep only matching rows.
mutate(new = col * 2)
Add a calculated column.

Graphs

hist(cows$estimate)
Quick histogram. Add breaks = 20 to change bar count.
ggplot(aes(x = , y = ))
Start a ggplot and set the axes.
geom_histogram() / geom_boxplot() / geom_violin()
Choose the shape. Join with +.
labs(title = , x = , y = )
Titles and axis labels.

Coming up: tests

binom.test(successes, trials)
Binomial test.
t.test(x, mu = 100)
One-sample t-test against a value.
t.test(a, b, paired = TRUE)
Related-samples t-test.
cor.test(x, y)
Correlation (term 2).

Check yourself

Six quick questions on the ideas above. Nothing is recorded.

When you're stuck

Getting stuck is part of learning to code, not a sign you're bad at it. Things to try, roughly in this order:

  1. Read the red text slowly. It usually names the exact object, file or symbol it choked on. Check the error decoder.
  2. Restart and re-run. Session ▸ Restart R, then run from line 1.
  3. Check the help. ?summarise in the console opens the help page, with examples at the bottom.
  4. Redo the learnr pre-lab tutorial for that week. They are built to practise exactly what the lab needs.
  5. Ask a coursemate or a GTA in the lab. They see the same five errors all day.
  6. Post on the PSYC121 Moodle forum or bring it to the weekly Q&A session. If you're stuck, dozens of others are too.

How to ask so you get a useful answer

Hard to help with

"I can't do exercise 5 in week 3."

Easy to help with

"Week 3, exercise 5. I loaded the data fine, but this line: wages %>% group_by(uk_region)… gives object 'wages' not found."

Always include the code you ran and the exact error. That alone usually gets you an answer in one reply.

Going further

  • PSYC121 lab materials — the department's own weekly lab sheets.
  • R for Data Science — free online book that the course itself recommends; uses the same tidyverse style.
  • Howell, Fundamental Statistics for the Behavioral Sciences — the department's endorsed textbook, with R sections. In the library.