Chapter 3 Libraries and Functions
R comes with many built-in functions, but its real power lies in the thousands of user-contributed packages available for specialized tasks. This chapter covers how to use functions and extend R’s capabilities with libraries.
3.1 Functions
A function takes inputs, performs an operation, and returns an output. You’ve already used several functions like c(), mean(), and data.frame(). Functions are called by their name followed by parentheses containing any arguments:
## [1] 4
## [1] 3.14
## [1] "2026-01-28"
3.2 Installing Packages
Packages extend R with new functions and datasets. You install a package once using install.packages():
To install multiple packages at once:
Packages download from CRAN, a repository of reviewed R packages. You only need to install a package once per computer.
3.3 Loading Packages
Installing puts a package on your computer, but you must load it in each R session to use its functions. Use library():
A common error is calling a function before loading its package:
Error: could not find function "str_to_upper"
This means you need to run library(stringr) first.
3.4 Calling Functions from Packages
3.4.2 Without Loading
You can also call a function without loading the entire package using the :: operator:
This syntax is useful when:
- You only need one function from a package
- Two packages have functions with the same name
- You want to make clear which package a function comes from
3.5 Packages Used in This Book
| Package | Purpose |
|---|---|
| tidyverse | Data manipulation and visualization |
| readxl | Read Excel files |
| haven | Read Stata, SPSS, and SAS files |
| WDI | World Bank data |
| fredr | Federal Reserve (FRED) data |
3.6 Exercises
Use the
?operator to look up the help page for theseq()function. Use it to create a sequence from 0 to 100 by increments of 5.Install the
havenpackage. Then use the::operator to check what functions it contains by typinghaven::and pressing Tab in RStudio.Calculate the natural log of 50 using
log(), then verify your answer usingexp().