๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R Split Apply Combine

split() cuts a data frame into a list of smaller frames. Each piece holds the rows for one group.

Split a frame by team

split() groups the rows by the team column. The blue piece keeps rows 2 and 4 from the full frame.

scores <- data.frame(name = c("Ana", "Ben", "Cid", "Dee"), team = c("red", "blue", "red", "blue"), score = c(12, 9, 15, 11))
parts <- split(scores, scores$team)
print(parts$blue)
print(parts$red)

Summarise each piece

lapply() runs mean over the score column of each piece. The result is a list with one mean per team.

scores <- data.frame(name = c("Ana", "Ben", "Cid", "Dee"), team = c("red", "blue", "red", "blue"), score = c(12, 9, 15, 11))
parts <- split(scores, scores$team)
means <- lapply(parts, function(piece) mean(piece$score))
print(means)

Combine the piece totals

lapply() first builds one total for each piece. do.call() then stacks those totals with rbind into one table.

scores <- data.frame(name = c("Ana", "Ben", "Cid", "Dee"), team = c("red", "blue", "red", "blue"), score = c(12, 9, 15, 11))
parts <- split(scores, scores$team)
totals <- lapply(parts, function(piece) c(total = sum(piece$score)))
combined <- do.call(rbind, totals)
print(combined)

Example

shop <- data.frame(item = c("pen", "pad", "pen", "pad"), branch = c("north", "north", "south", "south"), sold = c(5, 3, 7, 4))
parts <- split(shop, shop$branch)
totals <- lapply(parts, function(piece) c(total = sum(piece$sold)))
combined <- do.call(rbind, totals)
print(combined)

Key points

  • split() takes the frame first and the grouping column second.
  • The pieces keep the original row numbers from the full frame.
  • lapply() runs one summary over each piece in the list.
  • do.call() with rbind stacks the piece summaries into one table.
  • The combined table takes its row names from the group names.

In this example the shop frame splits into a north piece and a south piece. lapply() totals the sold column in each piece and do.call() stacks the two totals into one table with the branch names as row names.

Note

strsplit() cuts a piece of text, while split() cuts a whole frame by group.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What do the pieces from split() keep from the full frame?