R Data Frame Manipulation
Once data is loaded, you filter it, add columns, sort it, combine tables and compute group summaries. Base R has a function for each of these jobs.
| Task | Base R |
|---|---|
| keep rows / columns | subset(), df[rows, cols] |
| add or change columns | transform(), within(), df$new <- ... |
| sort | df[order(...), ] |
| group summaries | aggregate(), tapply() |
| join two tables | merge() |
| evaluate with columns as variables | with() |
| stack / reshape | rbind(), cbind(), reshape() |
We'll use a small orders table throughout:
orders <- data.frame(
id = 1:8,
customer = c("ana", "ben", "ana", "cai", "ben", "ana", "dee", "cai"),
product = c("pen", "book", "book", "pen", "lamp", "lamp", "book", "book"),
qty = c(10, 1, 2, 5, 1, 1, 3, 1),
price = c(1.5, 12, 12, 1.5, 30, 30, 12, 12)
)
orders id customer product qty price
1 1 ana pen 10 1.5
2 2 ben book 1 12.0
3 3 ana book 2 12.0
4 4 cai pen 5 1.5
5 5 ben lamp 1 30.0
6 6 ana lamp 1 30.0
7 7 dee book 3 12.0
8 8 cai book 1 12.0
subset(): filter rows and pick columns
subset() lets you refer to columns by name, without orders$:
orders <- data.frame(
id = 1:8,
customer = c("ana", "ben", "ana", "cai", "ben", "ana", "dee", "cai"),
product = c("pen", "book", "book", "pen", "lamp", "lamp", "book", "book"),
qty = c(10, 1, 2, 5, 1, 1, 3, 1),
price = c(1.5, 12, 12, 1.5, 30, 30, 12, 12)
)
subset(orders, product == "book" & qty > 1)
subset(orders, price > 10, select = c(customer, product)) id customer product qty price
3 3 ana book 2 12
7 7 dee book 3 12
customer product
2 ben book
3 ana book
5 ben lamp
6 ana lamp
7 dee book
8 cai book
transform(), with() and within()
transform() adds or modifies columns; with() evaluates an expression using the columns as variables:
orders <- data.frame(
id = 1:8,
customer = c("ana", "ben", "ana", "cai", "ben", "ana", "dee", "cai"),
product = c("pen", "book", "book", "pen", "lamp", "lamp", "book", "book"),
qty = c(10, 1, 2, 5, 1, 1, 3, 1),
price = c(1.5, 12, 12, 1.5, 30, 30, 12, 12)
)
orders <- transform(orders, total = qty * price, big = qty * price >= 30)
head(orders, 3)
with(orders, sum(total))
with(orders, tapply(total, customer, sum)) id customer product qty price total big
1 1 ana pen 10 1.5 15 FALSE
2 2 ben book 1 12.0 12 FALSE
3 3 ana book 2 12.0 24 FALSE
[1] 166.5
ana ben cai dee
69.0 42.0 19.5 36.0
Sorting with order()
order() returns row positions; use - for descending numeric order, and give several keys for tie-breaking:
orders <- data.frame(
customer = c("ana", "ben", "ana", "cai", "ben", "ana", "dee", "cai"),
product = c("pen", "book", "book", "pen", "lamp", "lamp", "book", "book"),
total = c(15, 12, 24, 7.5, 30, 30, 36, 12)
)
orders[order(-orders$total), ][1:3, ]
orders[order(orders$customer, -orders$total), ] customer product total
7 dee book 36
5 ben lamp 30
6 ana lamp 30
customer product total
6 ana lamp 30.0
3 ana book 24.0
1 ana pen 15.0
5 ben lamp 30.0
2 ben book 12.0
8 cai book 12.0
4 cai pen 7.5
7 dee book 36.0
aggregate(): group summaries
aggregate() with a formula computes a statistic per group. Use cbind() on the left for several columns and + on the right for several grouping variables:
orders <- data.frame(
customer = c("ana", "ben", "ana", "cai", "ben", "ana", "dee", "cai"),
product = c("pen", "book", "book", "pen", "lamp", "lamp", "book", "book"),
qty = c(10, 1, 2, 5, 1, 1, 3, 1),
total = c(15, 12, 24, 7.5, 30, 30, 36, 12)
)
aggregate(total ~ customer, data = orders, FUN = sum)
aggregate(cbind(qty, total) ~ product, data = orders, FUN = sum)
aggregate(total ~ customer, data = orders, FUN = length) # order count customer total
1 ana 69.0
2 ben 42.0
3 cai 19.5
4 dee 36.0
product qty total
1 book 7 84.0
2 lamp 2 60.0
3 pen 15 22.5
customer total
1 ana 3
2 ben 2
3 cai 2
4 dee 1
merge(): joining tables
merge() joins two data frames on common columns, like a SQL join. all.x = TRUE keeps unmatched rows from the left table (a left join):
customers <- data.frame(
customer = c("ana", "ben", "cai", "eve"),
city = c("Lisbon", "Oslo", "Lima", "Pune")
)
spend <- data.frame(customer = c("ana", "ben", "cai", "dee"),
total = c(69, 42, 19.5, 36))
merge(customers, spend) # inner join
merge(customers, spend, all.x = TRUE) # left join
merge(customers, spend, all = TRUE) # full outer join customer city total
1 ana Lisbon 69.0
2 ben Oslo 42.0
3 cai Lima 19.5
customer city total
1 ana Lisbon 69.0
2 ben Oslo 42.0
3 cai Lima 19.5
4 eve Pune NA
customer city total
1 ana Lisbon 69.0
2 ben Oslo 42.0
3 cai Lima 19.5
4 dee <NA> 36.0
5 eve Pune NA
Use by = "col" (or by.x/by.y when the names differ) to choose the key columns explicitly.
Putting it together
A typical pipeline: filter, compute, summarise and sort. Here with the built-in mtcars:
cars <- transform(mtcars, kpl = round(mpg * 0.4251, 1), model = rownames(mtcars))
cars <- subset(cars, hp > 100, select = c(model, cyl, hp, kpl))
by_cyl <- aggregate(kpl ~ cyl, data = cars, FUN = mean)
by_cyl[order(-by_cyl$kpl), ]
head(cars[order(-cars$kpl), ], 3) cyl kpl
1 4 11.000000
2 6 8.400000
3 8 6.428571
model cyl hp kpl
Lotus Europa Lotus Europa 4 113 12.9
Hornet 4 Drive Hornet 4 Drive 6 110 9.1
Volvo 142E Volvo 142E 4 109 9.1
Test yourself
Which call keeps only the rows of df with age > 30?
- subset(df, age > 30)
- filter(df$age > 30)
- df[age > 30]
- select(df, age > 30)
What does merge(a, b, all.x = TRUE) perform?
- An inner join
- A left join
- A right join
- A cross join
Which function computes the mean of y for each level of g in df?
- aggregate(y ~ g, data = df, FUN = mean)
- merge(y, g)
- order(y, g)
- transform(df, mean)