Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lesson 4 — R Basics: Objects, Vectors, Functions, and Getting Help

1Objectives

By the end of this lesson you will be able to:

  1. Store a value in an object and update it.

  2. Build a vector (a list of values) and pull pieces out of it.

  3. Use built-in functions, including ones that take more than one input.

  4. Look up how to use an unfamiliar function.

  5. 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] 20

The 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] 21

R 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 4

wait_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] 5
sum(wait_times)
[1] 22
mean(wait_times)
[1] 4.4
max(wait_times)
min(wait_times)
[1] 8
[1] 2
sort(wait_times)
[1] 2 3 4 5 8

Five 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] 3
wait_times[2:3]
[1] 5 2

2: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.14

Here, 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  9

seq() (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:

?mean

This 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, ...) 
NULL

This 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, ...) 
NULL

6Reading 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 found

Read 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

8Check your understanding

  1. Create an object called score holding the value 87, then update it to be 3 points higher, all with R code.

  2. Given hours <- c(6, 7, 5, 8, 6.5), write the R to find the average and the maximum.

  3. What will hours[4] return, using the vector from question 2?

  4. 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?