Menu
Coddy logo textTech

Grouping with split()

Part of the Logic & Flow section of Coddy's R journey. Lesson 39 of 64.

split(values, groups) puts each value into the group named by the matching element of groups. The result is a list with one element per group, named after the groups in sorted order:

amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
by_cat <- split(amounts, category)
print(names(by_cat))
print(by_cat[["food"]])

Output:

[1] "food" "fun"  "rent"
[1] 10 30

Combine split() with sapply() to compute one summary per group:

amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
by_cat <- split(amounts, category)
print(sapply(by_cat, sum))
print(sapply(by_cat, length))

Output:

food  fun rent 
  40   40   20 
food  fun rent 
   2    1    1 

The values can be text too, for example to group names by their first letter:

names <- c("ana", "bo", "al", "bea", "cy")
groups <- split(names, substr(names, 1, 1))
for (letter in names(groups)) {
  cat(letter, ":", paste(groups[[letter]], collapse = ", "), "\n")
}

Output:

a : ana, al 
b : bo, bea 
c : cy 

A group only exists when at least one value belongs to it, so check with %in% names() before reading a group that might be empty:

by_cat <- split(c(5, 7), c("food", "food"))
print("rent" %in% names(by_cat))

Output:

[1] FALSE
challenge icon

Challenge

Easy

Complete category_totals(amounts, categories). Return one line per category in alphabetical order, food: 40 (2 items), with the total amount and the number of amounts in that category.

The supplied code reads the amounts and the categories as two comma-separated lines of equal length and prints each returned line.

Try it yourself

category_totals <- function(amounts, categories) {
  # Write your code here
  character(0)
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(category_totals(as.numeric(strsplit(input[1], ",")[[1]]), strsplit(input[2], ",")[[1]]), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler