25 + 10[1] 35
50 / 4[1] 12.5
(25 + 35) / 2[1] 30
By the end of this chapter, you should be able to:
<- and recognize other assignment symbols;c();The previous chapter introduced RStudio, Projects, and R Markdown. We will now learn the small pieces of R code that appear in every later chapter. Try each example in a code chunk and look at the result before moving on. The examples in this chapter are deliberately small and familiar. We will introduce the course’s main dataset in the Data Import chapter.
Open djr.Rproj and create a new R Markdown document named 02-r-basics.Rmd. Save it beside 01-setup.Rmd. Keep using the same data and outputs folders for the rest of the book.
R understands ordinary arithmetic:
25 + 10[1] 35
50 / 4[1] 12.5
(25 + 35) / 2[1] 30
Parentheses work as they do in a calculator: R evaluates what is inside them first.
An object is a name that stores a value. Use <- to assign a value:
x <- 10
x[1] 10
Read the first line as “x gets 10.” R stores the value but does not print it until you type the object’s name.
Begin with short names that describe the value:
score <- 85
test_score <- 90When a name needs more than one word, use snake_case, with lowercase words separated by underscores. For example, test_score is easier to read than testscore. R is case-sensitive, so score and Score would be different objects.
You may see three assignment styles in R code:
| Code | Meaning | Use in this book |
|---|---|---|
x <- 10 |
Assign 10 to x from the left |
Preferred |
10 -> x |
Assign 10 to x from the right |
Valid, but uncommon |
x = 10 |
Assign 10 to x using an equals sign |
Valid in many situations, but not used for object assignment here |
We use <- because the object name appears first and because it clearly marks an assignment. The equals sign has another job you will see later: it names an option inside a function, written as option = value. Keeping <- for objects and = for named options makes code easier to read. Later, we will use == to ask whether two values are equal; = and == do not mean the same thing.
Use Alt + - on Windows or Option + - on Mac to insert <-.
R ignores text after #. Comments are notes for yourself or another reader. They can explain what a value means or why a step is needed.
# Age at the beginning of the course
age <- 20Good comments explain a decision. There is little value in writing # calculate the mean immediately above mean(student_ages) because the code already says that.
c() combines several values of the same kind into a vector. We will create three vectors now and use them to build a table later in this chapter:
student_names <- c("Ana", "Ben", "Chen")
student_ages <- c(20, 21, 22)
student_present <- c(TRUE, FALSE, TRUE)
student_ages[1] 20 21 22
Quotation marks identify text. TRUE and FALSE are logical values and do not use quotation marks. The three vectors have the same length because each position describes the same student: the first name, age, and attendance value all belong to Ana.
R can perform the same calculation on every value in a numeric vector. For example, add one to every age:
student_ages + 1[1] 21 22 23
A data table has variables in columns and observations in rows. The tidyverse uses a modern data frame called a tibble.
First load the tidyverse, then place the three vectors created above into a small table:
library(tidyverse)
students <- tibble(
name = student_names,
age = student_ages,
present = student_present
)
studentsOne row represents one student. The three columns contain each student’s name, age, and attendance. tibble() combines the related vectors by position, which is why they must contain the same number of values.
Tidy data are organized in a consistent way:
In students, name, age, and present are variables, so each has a column. Each student is one observation, so each student has one row.
“Tidy” describes the arrangement of a table; it is not another file type. A tibble can contain tidy or untidy data. We will learn how to make an untidy table tidy in Chapter 8, Join and Reshape.
The official tidyr introduction to tidy data provides more examples. The three rules above are enough for now.
Now that the table exists, look beneath each column name in the printed output. R shows a short label describing the kind of values stored there:
| Column | Type shown by R | Meaning |
|---|---|---|
name |
<chr> |
Character, or text |
age |
<dbl> |
Numeric values |
present |
<lgl> |
Logical values: TRUE or FALSE |
These are data types. A type matters because it determines which operations make sense. R can calculate the mean of age, but not the mean of student names. Later, imported tables will also contain <int> for whole numbers and <date> for calendar dates.
Text needs quotation marks when we type it. Logical values TRUE and FALSE do not. Missing information is normally represented by NA, not by zero.
A function is a named instruction that performs a task. Its name is followed by parentheses containing the information it needs. Use the numeric student_ages vector from the table:
sum(student_ages)[1] 63
mean(student_ages)[1] 21
median(student_ages)[1] 21
min(student_ages)[1] 20
max(student_ages)[1] 22
| Function | Calculation |
|---|---|
sum() |
Adds the values |
mean() |
Calculates the average |
median() |
Finds the middle value after sorting |
min() |
Finds the smallest value |
max() |
Finds the largest value |
The object student_ages is the input, or argument, given to each function. In later chapters, these same functions will summarize columns in much larger imported tables.
Many functions have optional arguments. Begin with the arguments needed for the task; open a help page later by typing a function name after ?, such as ?mean.
A pipe passes the result on its left to the function on its right. Modern R has a built-in pipe written as |>:
student_ages |>
mean()[1] 21
Read this as “start with student_ages, then calculate the mean.” This produces the same result as mean(student_ages).
You may also see an older pipe written as %>% in R tutorials and existing projects:
student_ages %>%
mean()[1] 21
For a simple example like this, both pipes do the same job. The main difference for beginners is where they come from:
| Pipe | Where it comes from | Use in this book |
|---|---|---|
|> |
Built into R | Used throughout the book |
%>% |
Available after loading the tidyverse | Shown here so you can recognize older code |
Pipes become especially useful when several steps are connected. We will use |> consistently in the later chapters.
More detailed debugging guidance is available in the Debugging appendix.
First create three vectors containing book titles, page counts, and whether the books are finished. Then use those vectors to create a tibble called books with three rows and these columns:
title, containing three book titles;pages, containing the number of pages in each book; andfinished, containing TRUE or FALSE.Print the tibble. Then write one sentence describing what one row represents.
| Function or symbol | What it does |
|---|---|
<- |
Assigns a value to an object name |
-> |
Assigns in the opposite direction; valid but uncommon |
= |
Can assign a value, but is reserved here for named function arguments |
# |
Adds a comment that R does not run |
c() |
Combines values into a vector |
sum() |
Calculates a total |
mean() |
Calculates an average |
median() |
Finds the middle value |
min() |
Finds the smallest value |
max() |
Finds the largest value |
tibble() |
Creates a tidyverse data table |
|> |
Passes an object to the next function |
%>% |
An older tidyverse pipe that appears in existing R code |
The official tibble() reference and tidyverse pipe guide provide more examples. The simple forms in this chapter are enough for the next lessons.