Applying Functions to Matrix Rows and Columns

One of the most famous and most used features of R is the *apply() family of functions, such as apply(), tapply(), and lapply(). Here, we’ll look at apply(), which instructs R to call a user-specified function on each of the rows or each of the columns of a matrix.

Using the apply() Function

This is the general form of apply for matrices:

apply(m,dimcode,f,fargs)

where the arguments are as follows:

  • m is the matrix.

  • dimcode is the dimension, equal to 1 if the function applies to rows or 2 for columns.

  • f is the function to be applied.

  • fargs is an optional set of arguments to be supplied to f.

For example, here we apply the R function mean() to each column of a matrix z:

> z [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.