Week 2 · Thursday, Oct 1 · Lecture
| Time | What |
|---|---|
| 1:30 | Warm-up: predict three lines |
| 1:40 | Reading a help page |
| 2:00 | Reading an error message, and the help routine |
| 2:20 | Data types and vectors |
| 2:40 | Coercion: why one bad value ruins a column |
| 2:55 | Names, factors, lists, matrices |
Learning goals: get yourself unstuck using R’s own documentation, and explain why every element of a vector has the same type.
Type along. Still no AI, including as a help source. Today is about becoming your own help desk.
⏱ 5 min
On paper, without running anything. What does R print?
Then run them. y is 10: assignment copies the value, not a live link.
z * 2 gives 2 4 6: R works on whole vectors at once. Hold on to that.
When you’re stuck, the fastest fix is someone handing you working code. It works today, and it does nothing for you next week.
Every time you
you build a path in your head you can use again, on any problem, without anyone’s help.
That is what fluency in a language is: knowing where to look and how to read what you find. Not memorizing functions.
Important
Today’s rule: if you’re stuck, the help page comes first, a person comes second. No chatbot.
Type ?median or help("median") in the Console. The page opens in the Help pane.
Every help page has the same sections:
| Section | What it tells you |
|---|---|
| Description | What the function does |
| Usage | How to call it, with each argument’s default |
| Arguments | What each argument means and what type it expects |
| Value | What comes back |
| See Also | Related functions. Often this is the one you needed |
| Examples | Runnable code |
Read Arguments first, then jump straight to Examples.
x has no default: you must supply itna.rm = FALSE has a default: optional, and this is what you get if you say nothing... means “other arguments, passed on to other methods”Operators have help pages too, in quotes or backticks:
sep or collapse?⏱ 6 min
Open ?paste. Using only the help page, work out the difference between sep and collapse. Then predict each of these before running it:
Check: "a c" "b c" · "a,c" "b,c" · "a c|b c" · "a,c|b,c"
sep goes between the pieces of each element. collapse glues the whole result into one string. Length 2 → length 2, or length 2 → length 1.
Also:
ls("package:stats") to see everything a package offersTip
Trust, in order: the official docs, the Posit Community forum, Stack Overflow answers that explain rather than just paste code.
⏱ 8 min
Two files, both with columns separated by tabs. One writes decimals with a period (12.5), the other with a comma (12,5, as in most of Latin America and Europe).
Find the function and the arguments that read each one correctly. Start from:
Then say how you’d check that the numbers really came in as numbers.
read.delim(file) for the first. read.delim(file, dec = ",") — or read.table(file, sep = "\t", dec = ",", header = TRUE) — for the second. Check with str(): you want num, not chr.
Where
Error in log("ten") :
The call that failed. Look at that line.
What
non-numeric argument to mathematical function
The reason. Usually a type problem.
An error is not a verdict on you. It is R telling you, as precisely as it can, what it could not do.
| Message | Usually means |
|---|---|
object 'x' not found |
Typo, wrong capitalization, or you never ran the line that creates x |
could not find function "x" |
Typo, or the package isn’t loaded with library() |
unexpected symbol / unexpected ')' |
A missing comma, bracket, or quote on or just before that line |
non-numeric argument to ... |
You gave text (maybe numbers stored as text) to something that needs numbers |
Note
Warning ≠ Error. An error stopped; nothing happened. A warning means R did it anyway and wants you to look. NAs introduced by coercion is a warning you must never ignore.
Tip
Step 4 is the one people skip and the one that solves it. If log(my_column) fails, try log(my_column[1]), then log(5). The step where it starts working tells you where the problem is.
⏱ 8 min
Run each line. For each one, write down (a) the where, (b) the what, and (c) the fix.
Then one more, which prints no error at all:
Missing ) · capital M, R is case-sensitive · "6" makes the whole vector text · and the last one is correct behavior: NA means “I don’t know”, so the mean is unknown too.
A question people can actually answer contains:
sessionInfo()Two ideas explain this, and most of R’s surprising behavior:
The rest of this lecture is those two sentences, unpacked.
Three questions, three functions:
| Question | Function | On plants$flowering |
|---|---|---|
| What type are the elements? | typeof() |
"logical" |
| What kind of object is this? | class() |
"logical" |
| Show me structure + a preview | str() |
logi [1:3] FALSE TRUE TRUE |
str() is the one you’ll use most3 obs. = 3 rows, 3 variables = 3 columnschr character · num double · int integer · logi logicalTip
str() on anything new, always, before you do anything else with it. It answers “what am I actually holding?”
A vector holds one type. Mix types, and R quietly converts everything to the most flexible one present:
logical → integer → double → complex → character
Important
No error, no warning. R did what you asked. This is why str() is a habit and not a chore.
⏱ 5 min
Open ?c and read what it says about combining different types. Then predict what typeof() reports for each, writing "logical", "integer", "double" or "character":
double · character · character · double · integer · double
One person typed a range instead of a number:
One bad cell turned 4 numbers into 4 strings. In a 50,000-row CSV you will not see it. str() will.
⏱ 8 min
Using plants2 from two slides ago:
str(plants2). Which column has the wrong type? What should it be?plants2$height_cm)plants2$height_cm[ROW] <- "15"plants2$height_cm <- as.numeric(plants2$height_cm)str(), then mean(plants2$height_cm)If you get NA, a step went wrong. Go back to step 3.
This is 80% of real data cleaning: str(), find the culprit, fix the value, convert, check.
⏱ 4 min
Make s, the whole numbers from from to to, and scaled, equal to s times k.
Use the variables, not typed-in numbers. Then check length(s).
⏱ 5 min
R ships with LETTERS, letters, month.name and month.abb. Print them.
Then build month_no: the numbers 1 to 12, with the abbreviated month names as their names. Look up October by name.
A list is a vector whose elements can be anything, of any type and any length.
trip <- list(place = "Monteverde", days = 3,
species_seen = c("quetzal", "sloth"))
str(trip)
#> List of 3
#> $ place : chr "Monteverde"
#> $ days : num 3
#> $ species_seen: chr [1:2] "quetzal" "sloth"
trip$species_seen #> "quetzal" "sloth"
trip[["days"]] #> [1] 3
trip["days"] # a LIST of length 1, not the numberA data frame is a list of equal-length vectors.
Everything about pulling pieces out of a data frame follows from that:
| You write | You get |
|---|---|
plants$species, plants[["species"]], plants[[1]] |
the column, a vector |
plants["species"], plants[1] |
a one-column data frame |
plants[2, 1] |
one value |
plants[, 1] |
all rows of column 1, a vector |
plants[2, ] |
row 2, a one-row data frame |
⏱ 6 min
Predict what class() returns for each: "data.frame", "character", "numeric" or "logical".
Then check with class(). One bracket keeps the box; two brackets take the contents out.
data.frame · character · numeric · data.frame · character · numeric · data.frame
⏱ 5 min
Which of these produced it? Reason it out first, then check.
matrix(c(4, 9, 10, 1, 5, 7), nrow = 3)matrix(c(4, 9, 10, 1, 5, 7), ncol = 2, byrow = TRUE)matrix(c(4, 1, 9, 5, 10, 7), nrow = 3, byrow = TRUE)matrix(c(4, 1, 9, 5, 10, 7), ncol = 2)1 and 3. Two different commands, one result: column-by-column with the values in column order, or row-by-row with the values in row order.
Same type only
vector — 1 dimensionmatrix — 2 dimensionsarray — n dimensionsMixed types
list — anything, any lengthdata.frame — a list of equal-length vectorsWith extras
factor — integer codes + labelsnames, dim, levelsA data frame is the rectangle you’ll work in all quarter. Everything under it is a vector, and every vector has one type.
?name opens a help page. Read Arguments, run Examples??"topic" and apropos() find functions when you don’t know the namecharacter. str() catches it$ and [[ ]] give a vector; [ ] with one index keeps a data frameTuesday DS (Oct 6, 9:50 am): Lesson 3: Seeking Help and Lesson 4: Data Structures.
Before Tuesday’s lecture: make a data/ folder inside stat266a and save gapminder_data.csv into it. We start from real data.
Next: Tuesday, Oct 6 · Exploring Data Frames
Stuck on the DS? Office hours after class, or Ed Discussion. Bring the exact error message.

STAT 266A · Fall 2026 · UC Santa Cruz