Processing entire rows or columns using the apply function

The apply function can apply a user-specified function to all rows or columns of a matrix and return an appropriate collection with the results.

Getting ready

This recipe uses no external objects or resources.

How to do it...

To process entire rows or columns using the apply function, follow these steps:

  1. Calculate row minimums for a matrix:
    > m <- matrix(seq(1,16), 4, 4)
    > m
    
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16
    
    > apply(m, 1, min)
    
    [1] 1 2 3 4
  2. Calculate column maximums for a matrix:
    > apply(m, 2, max)
    
    [1]  4  8 12 16
  3. Create a new matrix by squaring every element of a given matrix:
    > apply(m,c(1,2),function(x) x^2) [,1] [,2] [,3] [,4] [1,] 1 25 81 169 [2,] 4 ...

Get R: Recipes for Analysis, Visualization and Machine Learning 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.