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 01-r-basics.Rmd. Save it beside 00-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(numbers) because the code already says that.
c() combines several values of the same kind into a vector:
numbers <- c(2, 4, 6, 8)
numbers[1] 2 4 6 8
R can perform the same calculation on every value in a numeric vector:
numbers / 2[1] 1 2 3 4
A function is a named instruction that performs a task. Its name is followed by parentheses containing the information it needs. R provides simple functions for common calculations:
sum(numbers)[1] 20
mean(numbers)[1] 5
min(numbers)[1] 2
max(numbers)[1] 8
| Function | Calculation |
|---|---|
sum() |
Adds the values |
mean() |
Calculates the average |
min() |
Finds the smallest value |
max() |
Finds the largest value |
The object numbers is the input, or argument, given to each function.
In this book, we begin with the arguments needed for the task. Many functions have additional optional arguments. You can open a function’s help page later by typing its name after ?, such as ?mean.
Four types appear frequently in journalism data:
| Type shown by R | Meaning | Example |
|---|---|---|
<dbl> or <int> |
Numbers | 10, 3.5 |
<chr> |
Character, or text | "Alex" |
<lgl> |
Logical values | TRUE, FALSE |
<date> |
Calendar dates | 2025-01-01 |
Text needs quotation marks. Logical values TRUE and FALSE do not. Missing information is normally represented by NA, not by zero.
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 create a small table:
library(tidyverse)
students <- tibble(
name = c("Ana", "Ben", "Chen"),
age = c(20, 21, 22),
present = c(TRUE, FALSE, TRUE)
)
studentsOne row represents one student. The three columns contain each student’s name, age, and attendance.
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 untidy tables tidy in the Combine and Reshape chapter.
The official tidyr introduction to tidy data provides more examples. The three rules above are enough for now.
A pipe passes the result on its left to the function on its right. Modern R has a built-in pipe written as |>:
numbers |>
sum()[1] 20
Read this as “start with numbers, then calculate the sum.” This produces the same result as sum(numbers).
You may also see an older pipe written as %>% in R tutorials and existing projects:
numbers %>%
sum()[1] 20
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.
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 |
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.