3 R Basics
By the end of this chapter you should be able to:
- Explain how R runs code one line at a time, and why the order you run code in matters.
- Install a package once and load it in every session.
- Use R’s four basic data types: logical, integer, numeric, and character.
- Name variables clearly and consistently.
- Find help when your code breaks.
The last chapter introduced R, RStudio, and R Markdown, and the building blocks of a line of code. This chapter moves from reading code to writing it. It covers four things you will rely on in every assignment: how R actually runs your code, how to add new abilities to R with packages, how R stores different kinds of values, and what to do when something goes wrong.
None of it is spatial yet. But every map and every analysis later in the book is built from these pieces, and most of the problems students hit in the first weeks of the course come from one of them: chunks run out of order, a package that was never loaded, a number stored as text, or an error message nobody read.
3.1 How R runs your code
3.1.1 R is an interpreted language
R is an interpreted language. An interpreter is a program that executes instructions directly, one line at a time: it reads a line of code, translates it into something the computer can act on, runs it, and then moves on to the next line.
Other languages, such as C or Java, use a compiler instead. A compiler translates the whole program into machine code before any of it runs. A good analogy is translation at a conference. An interpreter is like a live translator who translates the speaker sentence by sentence, as the speech happens. A compiler is like a book translator, who translates the whole book before anyone reads a page.
Being interpreted is what makes R so good for exploring data. You can run a single line, look at the result, and decide what to do next, without building and running a whole program. That is exactly what you do in RStudio every time you press Ctrl+Enter.
3.1.2 Order matters
The flip side is that R only knows what you have run so far, in the order you ran it. Nothing stops you from running the chunks of an R Markdown file out of order, and when you do, the same code can leave a different result.
Here are three chunks. Each one stores a different number in a variable called day.
And here is a chunk that prints whatever day holds right now:
Run the three chunks top to bottom, then run the last one: day is 3. Now run the second chunk again, and then the last one: day is 2. The code in the file hasn’t changed, but the value in memory has, because R keeps whichever value it was given most recently. Before you click, try to predict what day will be.
In RStudio, the Environment pane always shows the current value of every variable, so it is the place to check what R is holding at any moment.
3.1.3 Knitting runs everything again
Out-of-order code is a quiet problem while you work, and a loud one when you knit. As the last chapter explained, knitting starts a fresh R session and runs every chunk from the top of the file to the bottom. If your file only worked because you ran chunk 5 before chunk 3, or because a variable you made in the Console is still sitting in the Environment, the knit fails. This is the most common reason an assignment won’t knit.
3.1.4 Rule one: think sequentially
The fix is a habit, and it is the first rule of this course: think sequentially.
- Run your code in order, top to bottom, at least while you are learning.
- Check the Environment pane to see which variables exist and what they hold.
- Every so often, choose Run > Restart R and Run All Chunks (Figure 3.1). This clears memory and reruns the whole file from the top, the same way knitting does. If it works, your file will knit.
3.2 Packages and libraries
3.2.1 What is a package?
Base R, the R you get when you install it, can do arithmetic, statistics, and basic plots. Almost everything else reaches you through packages. A package bundles functions, data, and documentation that someone else has written and tested, and that you can add to your own copy of R. A useful comparison is a car: base R is the engine, and packages are the add-ons, like GPS or a sunroof. In this course you will use the tidyverse for cleaning data, sf for spatial data, and tmap for maps, all of them packages.
Packages are worth using for four reasons:
- They save you from reinventing the wheel. Why write your own code for a complex task when an expert has already written, tested, and documented a function for it?
- They give you specialized tools for particular fields, from spatial analysis to genomics to finance.
- They are often faster than code you would write yourself, because they are optimized for speed and memory.
- They make your work reproducible. Anyone who installs the same packages can rerun your analysis.
3.2.2 Packages versus libraries
The words package and library are often used as if they meant the same thing, but there is a difference:
- A package is the bundle itself: the collection of code, data, and documentation.
- A library is the folder on your computer where installed packages are stored. You can have more than one.
You install a package into a library. Then, confusingly, you load it with a function called library(). In casual conversation people say “the tidyverse library,” and that’s fine, but it helps to know which is which.
3.2.3 CRAN
Most packages come from CRAN, the Comprehensive R Archive Network. CRAN is the official repository for R packages: think of it as R’s app store. It hosts thousands of packages, and each one passes a set of quality checks before it is published. You may later meet other sources, such as Bioconductor for genomics packages or GitHub for development versions, but everything in this course comes from CRAN.
3.2.4 Install once, load every session
Using a package takes two steps, and the difference between them matters (Table 3.1).
| Install | Load | |
|---|---|---|
| What it does | Downloads the package into your library | Makes the package’s functions available right now |
| How often | Once per computer (and again to update) | Every R session |
| How | RStudio’s Packages tab, or install.packages("tidyverse") |
library(tidyverse) |
| Quotes? | Yes, around the package name | No |
Belongs in your .Rmd file? |
No | Yes, at the top |
Installing downloads the package from CRAN and saves it in your library. You can do it with code, install.packages("tidyverse"), but in this course please use RStudio instead: open the Packages tab in the bottom-right pane, click Install, type the package name, and click Install again (Figure 3.2). Either way, you only need to do it once on each computer.
Never leave install.packages() in an R Markdown file. Knitting runs every line, so the file would download and reinstall the package every single time you knit.
Loading makes an installed package’s functions available in the current session. Put a library() call for each package you need at the top of every R Markdown file:
library(tidyverse)You need to load packages every time, because every R session, including the fresh one that knitting starts, begins with no packages loaded. Notice that library() doesn’t need quotation marks around the package name, while install.packages() does. That small difference trips up a lot of people.
If a file calls library() for a package that isn’t installed, R stops with an error like there is no package called 'tidyverse'. RStudio also tries to help: when you open a file that uses a package you don’t have, a yellow bar at the top of the Editor offers to install it for you.
3.3 Data types
Before you can analyze data, you need to know how R stores it. This section covers variables, vectors, and the four basic kinds of values R works with.
3.3.1 Variables, again
Recall from the last chapter that a variable is a named piece of data in memory, and that the assignment operator <- puts the value on its right into the name on its left:
# a character (text) variable
myName <- "Harry Potter"Read it out loud as “myName gets "Harry Potter".” In R we (usually) assign from right to left. The name always goes on the left of the arrow and the value on the right. "Harry Potter" -> myName also works, but it is easy to misread, so don’t use it.
3.3.2 Vectors
The most basic data structure in R is the vector: a sequence of values that all have the same data type. You make one with c(), short for combine:
Even a single value is a vector, with a length of one. That is why R prints [1] in front of 5 + 6: the answer is the first (and only) element of a vector. It is also why so many R functions work on whole vectors at once. temps * 2 doubles every temperature, with no loop required.
3.3.3 The four atomic data types
R has four main atomic data types, the basic kinds of values a vector can hold (Table 3.2).
| Type | What it stores | Example |
|---|---|---|
| logical | TRUE or FALSE |
isHot <- TRUE |
| integer | Whole numbers | myAge <- 21L |
| numeric | Numbers that can have decimals | myAccount <- 103.21 |
| character | Text, always in quotation marks | myName <- "Harry Potter" |
- Logical values are
TRUEandFALSE, written in capitals with no quotation marks. They are the answers to yes-or-no questions such as “is it raining?” or “is this county’s income above the median?” The next chapter uses them to pick out data. - Integer values are whole numbers. One detail surprises people: R stores a number you type, such as
21, as numeric unless you add anLto the end, as in21L. In practice you rarely need to care; R converts between integers and numerics for you. - Numeric values (also called doubles) are numbers that can have a decimal part, such as temperatures, incomes, or coordinates. Most numbers you work with will be numeric.
- Character values are text, also called strings. They always go inside quotation marks, which is how R tells the text
"Durham"apart from a variable namedDurham.
The function class() tells you what type a value is. Run this box, then try changing the values:
3.3.4 One type per vector
Because a vector holds values of a single type, mixing types forces R to convert some of them. This conversion is called coercion, and R picks the type that can hold everything without losing information. Text can hold anything, so if a vector contains even one character value, the whole vector becomes character:
The numbers have all turned into text (notice the quotation marks), and mean() can no longer average them. It returns NA with a warning. This is a very common source of trouble with real data: one stray letter or symbol in a column of numbers, such as "N/A" or "12,000", turns the entire column into text. When a calculation gives an odd result, class() is one of the first things to check.
3.3.5 Naming variables
Variable names can’t contain spaces, so names made of several words need a convention. Two are common (Table 3.3).
| Convention | How it works | Examples |
|---|---|---|
| camelCase | Join the words; capitalize every word after the first | whatIsTheTemp, popChapelHill |
| snake_case | Lowercase words joined by underscores | what_is_the_temp, pop_chapel_hill |
The tidyverse’s style guide uses snake_case, and so do most of the packages you will use. Either is fine in this course, as long as you pick one and use it consistently. Remember that names are case-sensitive, so popChapelHill and popchapelhill are different variables, and a file that mixes conventions is an easy place for that kind of typo to hide.
Whichever convention you use, choose names that say what the variable holds. popChapelHill tells a reader something; x or data2 does not. Short abbreviations, such as popCH, are fine if they are clear in context.
3.4 Debugging and getting help
3.4.1 Mistakes are a fact of life
Everyone’s code breaks, including the code of people who have programmed for decades. A helpful way to think about errors is as puzzles to solve, not failures. Each one is a chance to understand the code, the language, and the problem a little better, so the time you spend debugging is an investment in your skills, not time wasted. If you get stuck, that is part of learning to program, and it gets easier with practice.
When something breaks, work through it in order:
- Read the error message, word by word. It usually says what went wrong, and often names the object or line involved.
- Find the line that caused it. In a knit, the error names the chunk.
- Make a guess about the cause, change one thing, and run the code again.
3.4.2 The most common mistakes
Three mistakes account for most of the problems students run into early in the course. Check for these first.
- Not programming sequentially, and then being surprised when the file won’t knit (Section 3.1).
- Not storing files consistently, for example working straight out of the Downloads folder, so that R can’t find the data.
- Missing parentheses, commas, and quotation marks. One missing
)or"is enough to stop a program.
The second one has a simple fix. For now, save all of the files for an assignment in the same folder, inside your geog215 folder. When you knit, the HTML file appears in that folder; when you download data, save it there too. Then R will find everything. Don’t use the Desktop or Downloads folders as a place to work.
3.4.3 Getting help with a function
If you aren’t sure what a function does, or what arguments it takes, open its help page. Either of these works:
help(mean)
?meanThe help page opens in the Help tab of the bottom-right pane (Figure 3.3). Every help page has the same layout: a Description of what the function does, its Usage (how to call it, with each argument’s default value), a list of Arguments, and, at the bottom, Examples you can copy and run. The examples are often the quickest way to understand a function.
3.4.4 Getting help with an error
If you don’t understand an error message, copy it into a search engine. Someone has almost always run into the same error before, and the answer is often on Stack Overflow or the Posit Community forum. Leave out the parts that are specific to you, such as your variable names, so the search matches other people’s posts.
3.4.5 Using AI in this course
You may use AI tools such as Copilot to help explain an error message. For example, given the line my_age -> 39, an AI tool can point out that the assignment arrow is backwards and that you meant my_age <- 39. Use the explanation to understand the fix, then make the change yourself.
Don’t use AI to write your code. Generated code is often buggy, it often doesn’t follow the course’s coding standards (code that doesn’t won’t receive credit), and, most importantly, the point is for you to learn to write R yourself.
3.4.6 Getting help from people
In GEOG 215 there are three ways to get help from the teaching team:
- Post in the Help! channel in the course’s Microsoft Teams team. The TAs and the instructor check it daily, and your classmates can learn from the answer too.
- Come to office hours, in person or online, with the instructor or a TA.
- Email the instructor for anything private, such as grades or accommodations.
When you ask, include the code you ran and the full error message. “My code doesn’t work” is hard to answer; “library(tidyverse) gives there is no package called 'tidyverse'” can be answered in one line.
3.5 Check your understanding
An R Markdown file has three chunks:
day <- 1,day <- 2, andday <- 3. You run the third chunk, then the first. What doesdayhold now?How often do you need to install a package on your computer?
Which line belongs at the top of an R Markdown file?
A library is the folder on your computer where installed packages are stored.
What does
class("103.21")return?What type is the vector
c(1, 2, "three")?Which variable name follows the snake_case convention?
Which command opens the help page for the function
round()?
R keeps whichever value it was given most recently. The order you ran the chunks matters, not their order in the file.
A vector holds one type. Text can hold anything, so one character value turns the whole vector into character.
3.6 Summary
- R is an interpreted language: it runs one line at a time, in the order you run it. The same chunks run in a different order can leave different values in memory.
- Knitting reruns every chunk from the top in a fresh session. Think sequentially, check the Environment pane, and use Restart R and Run All Chunks to make sure your file will knit.
- A package is a bundle of code written by others; a library is the folder where installed packages live. Most packages come from CRAN.
- Install a package once per computer, with the Packages tab. Load it in every session with
library(), at the top of every R Markdown file. Never putinstall.packages()in an.Rmdfile. - A vector is a sequence of values of one type, made with
c(). R’s four atomic types are logical, integer, numeric, and character;class()tells you which one you have. Mixing types coerces the whole vector, usually to character. - Name variables in camelCase or snake_case, consistently, with names that say what they hold.
- Errors are normal. Read the message, find the line, and check the common mistakes first. For help, use
?function, search the error, and ask on Teams or in office hours. Use AI to explain errors, not to write your code.
3.7 Exercises
Order matters. Make a new R Markdown file with three chunks:
x <- 10,x <- x * 2, andx. Run them in order and note the result. Now run the second chunk two more times, then the third. What isx, and why? What willxbe after you knit?Install and load. Using the Packages tab, install the
nycflights13package, which you will use in a later chapter. Then load it in a chunk at the top of your file and knit. What happens if you remove thelibrary()line and runhead(flights)?Data types. Create one variable of each atomic type, describing yourself or your hometown (for example, the town’s name, its population, its area in square miles, and whether you live there now). Use
class()on each one. Did the population come out as integer or numeric? Why?Coercion. Predict the type of each vector below, then check with
class(). Which result surprised you?c(1, 2, 3.5) c(TRUE, FALSE, 1) c(1, "2", 3) c(TRUE, "FALSE")Naming. Rewrite these names in snake_case and in camelCase:
median household income,Number of Counties,pop 2020. Which convention will you use this semester?Read a help page. Open the help page for
seq(). What do itsfrom,to, andbyarguments do? Use the Examples section to make the sequence 2, 4, 6, …, 20.Debug. Each line below has one mistake. Find and fix it, and say which of the “most common mistakes” it is.
my_age -> 39 myCities <- c("Raleigh", "Durham, "Chapel Hill") round(mean(c(4, 8, 15), digits = 1) library("tidyverse
3.8 Further reading
- R for Data Science (2nd ed.) by Hadley Wickham, Mine Çetinkaya-Rundel, and Garrett Grolemund, free at https://r4ds.hadley.nz. The chapters “Workflow: basics” and “Workflow: getting help” cover the same ground as this chapter.
- The tidyverse style guide, https://style.tidyverse.org, explains snake_case and many other conventions for writing readable R code.
- What They Forgot to Teach You About R by Jenny Bryan and Jim Hester, https://rstats.wtf, has practical advice on project folders and working sequentially.
install.packages(), then load it in
each session with library().
The kind of value R is storing. The four main atomic types are logical,
integer, numeric, and character; class() tells you which
you have.
The data type for TRUE and FALSE values,
written in capitals with no quotation marks.
The data type for whole numbers. R stores a typed number as numeric
unless you add an L, as in 21L. Shown as
<int> by glimpse().
The data type for numbers that can have a decimal part, such as 103.21.
Also called double, and shown as <dbl> by
glimpse().
The data type for text, also called strings. Character values always go
inside quotation marks, as in "Chapel Hill".
In R, a named piece of memory that holds data, such as
months <- 12. In a dataset, a measured characteristic,
such as median income; each Census variable has a code.
The integrated development environment (IDE) where you write and run R.
R does the computing; RStudio is the workspace around it.
A document format (.Rmd) that mixes formatted text with
chunks of R code. Knitting it runs the code and builds a finished
report.
A block of R code inside an R Markdown file, starting with
```{r} and ending with three backticks.
A language, like R, that runs code one line at a time: an interpreter
reads each line, translates it, and runs it before moving on.
A set of lines and blocks of code that work together to do a whole job.
R runs a program from top to bottom, so order matters.
A program that translates a whole program into machine code before any
of it runs. C and Java are compiled; R is interpreted.
The RStudio pane (top right) that lists the variables and data currently
in memory.
To build an R Markdown file into a finished document (HTML, PDF, or
Word). Knitting reruns every code chunk from the top in a fresh R
session.
One run of R, from start to finish. A new session starts with an empty
Environment and no packages loaded; knitting always starts a fresh one.
The RStudio pane (bottom left) where R runs commands and prints results,
warnings, and errors. Nothing typed here is saved.
The RStudio pane (top left) where you write and save scripts and R
Markdown files. Code here can be kept and run again.
Code that takes inputs (arguments), does a job, and returns an output,
such as mean(temps).
A family of R packages (including dplyr,
ggplot2, and readr) for reading,
cleaning, reshaping, summarizing, and plotting data, all designed to
work together.
“Simple features”: the R package for spatial vector data. An sf object
is a data frame with a geometry column holding each row’s point, line,
or polygon.
An R package for making thematic maps quickly, with sensible defaults.
The ability for anyone to rerun an analysis from its code and data and
get the same result.
The folder on your computer where installed packages are stored. You
install packages into a library, then load them with
library().
The Comprehensive R Archive Network: the official website for
downloading R and most R packages.
A sequence of values that R stores together, made with c(),
such as c(71, 75, 68).
<-, the arrow that stores the value on its right in the
name on its left. Read x <- 5 as “x gets 5.”
The middle value when values are sorted, so half are above and half
below. Unlike counts, medians can’t be added across areas.
R converting values from one data type to another. Mixing types in one
vector coerces them all to the type that can hold everything, usually
character.
A way of naming variables that joins words and capitalizes every word
after the first, as in popChapelHill.
Combining two tables by matching rows on a shared key column, such as
attaching Census data to boundaries by GEOID with
left_join().
A way of naming variables with lowercase words joined by underscores, as
in pop_chapel_hill. The tidyverse style guide uses it.
Treating capital and lowercase letters as different. In R,
Months and months are two different names.
Finding and fixing the mistakes (bugs) in code: read the error message,
find the line, make a guess, and test it.
An input to a function, written inside its parentheses.
A function’s documentation, opened with ?name or
help(name). Every help page has a Description, Usage,
Arguments, and Examples.