1Objectives¶
By the end of this lesson you will be able to:
Store a value in an object and update it.
Build a vector (a list of values) and pull pieces out of it.
Use built-in functions, including ones that take more than one input.
Look up how to use an unfamiliar function.
Read a common error message and fix it.
This is the longest lesson in the book, because it’s where the actual vocabulary of R lives. Everything from Lesson 5 onward reuses these five ideas constantly.
2Objects: giving a value a name¶
An object is just a name that holds a value, so you can use that value again
later without retyping it. You create one with <- (the assignment arrow —
type < then -; RStudio and JupyterHub both also accept the keyboard shortcut
Alt + - to insert it for you).
age <- 20
age[1] 20The first line stores 20 in an object named age (quiet — no output). The
second line asks “what is age?” and R answers.
Objects can be updated by reusing their own name:
age <- age + 1
age[1] 21R read the old value of age (20), added 1, and stored the result back into
age under the same name — this is one of the most common patterns you’ll write.
3Vectors: a list of values with one name¶
Most of the time in statistics you have more than one number. A vector bundles
several values under one name, built with the function c() (think “combine”):
pets <- c("cat", "dog", "fish")
pets[1] "cat" "dog" "fish"wait_times <- c(3, 5, 2, 8, 4)
wait_times[1] 3 5 2 8 4wait_times now holds five numbers — say, minutes five customers waited in line at
a coffee cart — as a single object. Every value in a vector has to be the same
type (all numbers, or all text) — you’ll meet the exceptions to this later in the
course, but for now just remember c() bundles same-type values together.
3.1Functions that work on a whole vector at once¶
This is where R starts to feel powerful: many functions take a whole vector and summarize it in one step.
length(wait_times)[1] 5sum(wait_times)[1] 22mean(wait_times)[1] 4.4max(wait_times)
min(wait_times)[1] 8
[1] 2sort(wait_times)[1] 2 3 4 5 8Five different questions about the same five numbers — “how many?”, “what’s the total?”, “what’s the average?”, “what’s the biggest/smallest?”, “put them in order” — five different one-word functions. This pattern (a function name, a vector inside its parentheses) is the single most common shape of code you’ll write all semester.
3.2Pulling one value out of a vector: indexing¶
Every position in a vector has a number, starting at 1 (not 0). Square
brackets [ ] after a vector’s name pull out the value(s) at a position:
wait_times[1][1] 3wait_times[2:3][1] 5 22:3 means “2 through 3” — a quick way to write a small range of positions. You’ll
mostly use indexing for spot-checks; the mosaic functions in
Lesson 5/Lesson 7 will do the heavy summarizing for you.
4Functions: verbs with parentheses¶
You’ve already used several functions (c(), mean(), sort(), length()).
The pattern is always: function_name(input). Some functions take more than
one input, separated by commas, and some of those inputs have names:
round(3.14159, 2)[1] 3.14Here, 3.14159 is the value to round, and 2 says “to 2 decimal places.” You
could also write round(3.14159, digits = 2) — naming the second input makes the
code more self-explanatory, and becomes necessary once functions take several
optional inputs (you’ll see this constantly starting in Lesson 5, with things like
data = ).
seq(1, 10, by = 2)[1] 1 3 5 7 9seq() (short for “sequence”) built the numbers 1 through 10, counting by 2.
rep("meow", 3)[1] "meow" "meow" "meow"rep() (short for “repeat”) repeated "meow" three times into a vector.
5Getting help without memorizing everything¶
You are not expected to memorize R. Professional data analysts look things up constantly — the actual skill is knowing how to look something up.
In RStudio or a JupyterHub notebook, put a question mark before any function name and run it:
?meanThis opens a Help page (a separate pane in RStudio; a pop-up or side panel in a
notebook) with the function’s description, every input it accepts, and runnable
examples at the bottom. This book won’t reproduce Help pages here since they open
in your own tool, but you should try ?mean yourself right now if you have R open.
A quicker, in-console way to see just a function’s inputs (no explanation, just the
“shape” of the call) is args():
args(round)function (x, digits = 0, ...)
NULLThis tells you round() takes a value x and an optional digits (which defaults
to 0 if you don’t specify it) — matching what you saw above.
args(mean)function (x, ...)
NULL6Reading an error message¶
Sooner or later you will run a line and see red text instead of an answer — this
is completely normal and happens to everyone, including your instructor. Here’s a
real one. Suppose you meant to type wait_times but your fingers slipped:
mean(wiat_times)Error: object 'wiat_times' not foundRead error messages from the actual words, not the scary red color:
object 'wiat_times' not found is R telling you, plainly, that nothing named
wiat_times exists yet — almost always a typo, or a line you forgot to run first.
Compare the misspelled name to what you actually created (wait_times, from
earlier in this lesson) and the fix becomes obvious.
This is the single most common error beginners see. Lesson 12 (coming soon) collects a full table of common errors like this one and how to fix each.
7Summary¶
<-stores a value in an object; the object’s name can be reused and updated.c()bundles several same-type values into a vector;[ ]pulls specific positions back out (counting starts at 1).Functions follow
function_name(input); some inputs have names, likeround(x, digits = 2).?function_nameopens full documentation;args(function_name)shows just its inputs.Error messages are meant to be read literally — they almost always point straight at the fix.
8Check your understanding¶
Create an object called
scoreholding the value87, then update it to be 3 points higher, all with R code.Given
hours <- c(6, 7, 5, 8, 6.5), write the R to find the average and the maximum.What will
hours[4]return, using the vector from question 2?You run
Mean(hours)(capital M) and get an error. Using what you learned about reading errors, and remembering that R is case-sensitive, what’s gone wrong?