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

R Apply Function

apply runs one function over the rows or the columns of a matrix. One call does the work of a whole set of separate calls.

Totals for each row

Margin 1 hands each row to sum in turn. The result holds one total for each row.

m <- matrix(1:6, nrow = 2)
print(m)
print(apply(m, 1, sum))

The largest in each column

Margin 2 hands each column to max in turn. The result holds the largest value of each column.

m <- matrix(1:6, nrow = 2)
print(apply(m, 2, max))

Apply over an array

An array margin works the same way. Margin 3 hands each slice of the array to sum.

arr <- array(1:8, dim = c(2, 2, 2))
print(apply(arr, 3, sum))

A function written in the call

The unnamed function takes one row and returns the gap between its largest and smallest values. apply runs it once for each row of the matrix.

m <- matrix(c(8, 3, 12, 5, 7, 20), nrow = 2)
print(apply(m, 1, function(row) max(row) - min(row)))

Apply on a plain vector fails

A plain vector has no dimensions and no margins. apply stops with an error about the length of dim.

v <- c(3, 7, 2)
print(apply(v, 1, sum))

Example

marks <- matrix(c(70, 80, 90, 60, 75, 95), nrow = 3)
print(marks)
print(apply(marks, 1, mean))
print(apply(marks, 2, sum))

Key points

  • apply takes the data, a margin number and a function.
  • A margin is the direction apply works along.
  • Margin 1 works over the rows of a matrix.
  • Margin 2 works over the columns of a matrix.
  • The result holds one value for each row or column picked.
  • apply also works over the margins of an array.
  • A function written inside the call can do the work.

In this example margin 1 averages the two marks in each row. Margin 2 then totals each column of marks. One matrix gives both a row summary and a column summary.

Note

apply needs data with dimensions, so a plain vector fails.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does margin 2 make apply work over?