R Packages and Libraries — Extending R's Power
Learning Objectives
By the end of this tutorial, you will be able to:
- Install, load, and manage R packages
- Understand the CRAN, Bioconductor, and GitHub package ecosystems
- Use the tidyverse meta-package effectively
- Create your own R package with
devtools - Troubleshoot common package issues
What Are Packages?
An R package is a bundle of functions, data, and documentation that extends R's capabilities.
| Source | Description | Install Command |
|---|---|---|
| CRAN | Comprehensive R Archive Network | install.packages() |
| Bioconductor | Bioinformatics packages | BiocManager::install() |
| GitHub | Development versions | devtools::install_github() |
| R-Forge | Collaborative development | install.packages(repos = "http://R-Forge.R-project.org") |
Installing Packages
# Install from CRAN
install.packages("ggplot2")
# Install multiple packages
install.packages(c("dplyr", "ggplot2", "tidyr", "readr"))
# Install from GitHub
install.packages("devtools")
devtools::install_github("tidyverse/ggplot2")
# Install from Bioconductor
install.packages("BiocManager")
BiocManager::install("GenomicRanges")
# Install development version
devtools::install_github("user/package", ref = "dev")
Loading Packages
# Load package
library(ggplot2)
# Load with namespace
ggplot2::ggplot()
# See what's loaded
search()
# [1] ".GlobalEnv" "package:ggplot2" "package:stats"
# [4] "package:graphics" "package:grDevices" "package:utils"
# [7] "package:datasets" "package:methods" "package:base"
# Detach package
detach("package:ggplot2", unload = TRUE)
Essential Packages
Tidyverse Ecosystem
# Install entire tidyverse
install.packages("tidyverse")
# Load it
library(tidyverse)
# Attaching core packages: ggplot2, tibble, tidyr, readr, purrr, dplyr, stringr, forcats
| Package | Purpose |
|---|---|
ggplot2 | Data visualization |
dplyr | Data manipulation |
tidyr | Data tidying |
readr | Fast data import |
purrr | Functional programming |
stringr | String manipulation |
forcats | Factor handling |
tibble | Modern data frames |
Data Science
| Package | Purpose |
|---|---|
caret | Machine learning |
randomForest | Random forests |
xgboost | Gradient boosting |
glmnet | Regularized regression |
cluster | Clustering |
factoextra | Clustering visualization |
Statistics
| Package | Purpose |
|---|---|
stats | Base statistics (built-in) |
MASS | Statistical methods |
survival | Survival analysis |
lme4 | Mixed-effects models |
bayesplot | Bayesian analysis |
Package Information
# Package details
packageDescription("ggplot2")
# Available functions
ls("package:ggplot2")
# Vignettes
vignette(package = "ggplot2")
vignette("ggplot2-specs")
# Changelog
news(package = "ggplot2")
# Dependencies
tools::package_dependencies("ggplot2")
# Update packages
update.packages()
Creating R Packages
Package Structure
mypackage/
+-- DESCRIPTION # Package metadata
+-- NAMESPACE # Exported functions
+-- R/ # R code files
| +-- function1.R
| +-- function2.R
+-- man/ # Documentation
| +-- function1.Rd
| +-- function2.Rd
+-- data/ # Data files
+-- tests/ # Test files
| +-- testthat/
+-- vignettes/ # Vignettes
Using devtools
# Install devtools
install.packages("devtools")
# Create package
devtools::create("mypackage")
# Add function
devtools::use_r("function1")
# Add test
devtools::use_testthat()
devtools::use_test("function1")
# Add documentation
devtools::document()
# Build and check
devtools::build()
devtools::check()
# Install locally
devtools::install()
# Run tests
devtools::test()
DESCRIPTION File
Package: mypackage
Title: My Awesome Package
Version: 0.1.0
Authors@R: person("John", "Doe", email = "[email protected]", role = c("aut", "cre"))
Description: Does awesome things with R.
License: MIT + file LICENSE
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.2.3
Depends: R (>= 3.5.0)
Imports:
dplyr,
ggplot2
Suggests:
testthat (>= 3.0.0),
knitr,
rmarkdown
Troubleshooting
Common Issues
# Package not found
install.packages("package_name")
# Version conflicts
packageVersion("ggplot2")
# Reinstall
remove.packages("ggplot2")
install.packages("ggplot2")
# Load conflicts
conflicts(detail = TRUE)
# Check conflicts
conflicts(filter = c("filter", "lag")) # dplyr vs stats
# Use namespace to resolve
dplyr::filter()
stats::filter()
Package Dependencies
# See dependencies
tools::package_dependencies("tidyverse")
# Install all dependencies
devtools::install_deps("mypackage")
# Check for missing packages
missing <- setdiff(
tools::package_dependencies("tidyverse")$tidyverse,
installed.packages()[, "Package"]
)
Practice Exercises
Exercise 1: Package Explorer
Write a function that lists all functions in a package.
Solution
list_functions <- function(package_name) {
if (!requireNamespace(package_name, quietly = TRUE)) {
stop(paste("Package", package_name, "is not installed"))
}
ls(paste0("package:", package_name))
}
list_functions("ggplot2")
Key Takeaways
install.packages()installs from CRAN — one-time per R versionlibrary()loads a package — every session- Tidyverse is a meta-package — loads core data science packages
- Use
devtoolsto create packages — modern package development workflow - DESCRIPTION defines package metadata — name, version, dependencies
devtools::document()generates documentation from roxygen2 commentsdevtools::check()runs comprehensive checks before submission
Next: Learn about R Data Import/Export — working with various data formats.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions