Packages
## Learning Objectives
- Install and load R packages
- Understand package ecosystem
- Work with CRAN and GitHub packages
- Master tidyverse basics
## Package Basics
### What is a Package?
- Collection of R functions, data, and documentation
- Extends R's capabilities
- Distributed via CRAN, GitHub, Bioconductor
### Installed Packages
```r
# List all installed packages
installed.packages()
# Check if package is installed
"ggplot2" %in% installed.packages()
# Number of installed packages
nrow(installed.packages())
```
## Installing Packages
### From CRAN
```r
# Install single package
install.packages("ggplot2")
# Install multiple packages
install.packages(c("dplyr", "tidyr", "readr"))
```
### From GitHub
```r
# Need devtools or remotes
install.packages("remotes")
# remotes::install_github("owner/repo")
remotes::install_github("tidyverse/dplyr")
```
### From Bioconductor
```r
# Bioconductor packages need special installation
if (!require("BiocManager"))
install.packages("BiocManager")
BiocManager::install("DESeq2")
```
### Installing with Dependencies
```r
# install.packages installs dependencies automatically
install.packages("tidyverse")
# Check dependencies
tools::package_dependencies("ggplot2")
```
## Loading Packages
### library vs require
```r
# library() throws error if not found
library(ggplot2)
# require() returns TRUE/FALSE, more gentle
if (!require(ggplot2)) {
install.packages("ggplot2")
library(ggplot2)
}
```
### Namespace
```r
# Use :: to call without loading
dplyr::filter(df, condition)
# ggplot2::ggplot
# tidyr::pivot_longer
```
### Detaching
```r
# Unload package
detach("package:ggplot2", unload = TRUE)
```
## Tidyverse
### Overview
Tidyverse is a collection of R packages for data science.
| Package | Purpose |
|---------|---------|
| dplyr | Data manipulation |
| tidyr | Data tidying |
| readr | Data import |
| ggplot2 | Visualization |
| purrr | Functional programming |
| tibble | Modern dataframes |
| stringr | String manipulation |
| forcats | Factor handling |
### Installing Tidyverse
```r
# Install all tidyverse packages
install.packages("tidyverse")
# Load tidyverse
library(tidyverse)
```
## tibble Package
### Modern Dataframes
```r
# tibble is a modern dataframe
library(tibble)
# Create tibble
tb <- tibble(
name = c("Alice", "Bob"),
age = c(25, 30)
)
class(tb) # "tbl_df" "tbl" "data.frame"
# Print (better formatting)
print(tb)
tb
```
### tribble - Row-wise Tibble
```r
# Create from rows
tb <- tribble(
~name, ~age, ~score,
"Alice", 25, 95.5,
"Bob", 30, 87.3,
"Charlie", 35, 92.1
)
```
### tibble vs data.frame
```r
# tibble: doesn't change variable types
df <- data.frame(x = 1:3, y = c("a", "b", "c"))
str(df) # y becomes Factor
tb <- tibble(x = 1:3, y = c("a", "b", "c"))
str(tb) # y stays character
# tibble: no partial matching
df <- data.frame(one = 1)
df$o # Works (partial)
tb <- tibble(one = 1)
# tb$o # Error
# tibble: shows dimensions
tb
# # A tibble: 3 x 2
```
## readr Package
### Reading Data
```r
library(readr)
# Read CSV
df <- read_csv("data.csv")
# Read TSV
df <- read_tsv("data.tsv")
# Read delimited
df <- read_delim("data.txt", delim = "|")
```
### Writing Data
```r
library(readr)
# Write CSV
write_csv(df, "output.csv")
# Write TSV
write_tsv(df, "output.tsv")
```
### Parsing Options
```r
# Specify column types
df <- read_csv("data.csv",
col_types = cols(
name = col_character(),
age = col_integer(),
score = col_double()
))
# Skip lines
df <- read_csv("data.csv", skip = 2)
# No header
df <- read_csv("data.csv", col_names = FALSE)
```
## tidyr Package
### Data Tidying
```r
library(tidyr)
# Gather (wide to long)
df <- data.frame(
name = c("Alice", "Bob"),
math = c(90, 85),
science = c(95, 88)
)
gather(df, subject, score, math, science)
# name subject score
# Alice math 90
# Bob math 85
# Alice science 95
# Bob science 88
# spread (long to wide)
gather(df, subject, score, math, science) %>%
spread(subject, score)
```
### Pivot Functions (Modern)
```r
library(tidyr)
# Pivot longer (wide to long)
df <- data.frame(
name = c("Alice", "Bob"),
math = c(90, 85),
science = c(95, 88)
)
pivot_longer(df, cols = c(math, science),
names_to = "subject",
values_to = "score")
# Pivot wider (long to wide)
pivot_wider(df, names_from = subject, values_from = score)
```
### Separate and Unite
```r
# Separate column
df <- data.frame(
name = c("Alice Smith", "Bob Jones"),
age = c(25, 30)
)
separate(df, name, into = c("first", "last"), sep = " ")
# first last age
# 1 Alice Smith 25
# 2 Bob Jones 30
# Unite columns
unite(df, "full_name", first, last, sep = " ")
# full_name age
# 1 Alice Smith 25
# 2 Bob Jones 30
```
### Handle Missing Values
```r
# Drop rows with any NA
drop_na(df)
# Drop rows with NA in specific columns
drop_na(df, age)
# Fill NA with value
fill(df, column_name)
# Fill NA with previous value
fill(df, column_name, .direction = "up")
# Replace NA with specific value
replace_na(df, list(column_name = 0))
```
## dplyr Package
### Core Functions
```r
library(dplyr)
# select - choose columns
select(df, name, age)
select(df, -score) # Exclude
# filter - choose rows
filter(df, age > 25)
filter(df, age > 25 & score < 90)
# mutate - add/modify columns
mutate(df, avg = (math + science) / 2)
mutate(df, grade = ifelse(score >= 90, "A", "B"))
# summarize - aggregate
summarize(df, mean_age = mean(age))
summarize(df, n = n()) # Count rows
# arrange - sort
arrange(df, age)
arrange(df, desc(age))
```
### Chaining
```r
# Pipe operator %>%
df %>%
filter(age > 25) %>%
select(name, age) %>%
arrange(age)
```
### Group By
```r
df <- data.frame(
group = c("A", "A", "B", "B"),
value = c(10, 20, 30, 40)
)
df %>%
group_by(group) %>%
summarize(mean = mean(value),
sum = sum(value),
n = n())
```
## stringr Package
### String Operations
```r
library(stringr)
# Length
str_length(c("apple", "banana")) # 5 6
# Case
str_to_upper("hello") # "HELLO"
str_to_lower("HELLO") # "hello"
str_to_title("hello world") # "Hello World"
# Trim
str_trim(" hello ") # "hello"
```
### Pattern Matching
```r
# Detect pattern
str_detect(c("apple", "banana"), "an") # FALSE TRUE
# Extract matches
str_extract("abc123def", "[0-9]+") # "123"
# Replace
str_replace("apple", "p", "z") # "azple"
str_replace_all("banana", "a", "o") # "bonono"
# Split
str_split("a-b-c", "-") # list("a", "b", "c")
```
### Combining
```r
# Concatenate
str_c("Hello", "World") # "HelloWorld"
str_c("Hello", "World", sep = " ") # "Hello World"
# Join vector
str_c(c("a", "b"), collapse = "-") # "a-b"
```
## forcats Package
### Factor Operations
```r
library(forcats)
# Change order
f <- factor(c("small", "large", "medium"))
fct_relevel(f, "small", "medium", "large")
# Reverse
fct_rev(f)
# Reorder by frequency
f <- factor(c("b", "a", "b", "c", "a"))
fct_infreq(f) # b a c (by frequency)
# Lump (group rare values)
f <- factor(c("a", "a", "a", "b", "c"))
fct_lump(f, n = 2) # a b Other
```
## Updating Packages
### Update All
```r
# Update all packages
update.packages()
# Update specific package
install.packages("dplyr")
```
### Check Versions
```r
# Package version
packageVersion("dplyr")
# R version
R.version.string
```
## Summary
- Packages extend R functionality
- `install.packages()` from CRAN, `remotes::install_github()` from GitHub
- `library()` loads package, `detach()` unloads
- Tidyverse is a coherent collection of data science packages
- tibble is a modern, stricter dataframe
- dplyr provides grammar of data manipulation
- tidyr for data tidying (gather, spread, pivot)
- stringr for string manipulation
- forcats for factor handling
- Keep packages updated with `update.packages()`
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →