O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

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

  1. Calculate row minimums for the 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 
  1. Calculate column maximums for the matrix:
> apply(m, 2, max) 
 
[1]  4  8 12 16 
  1. Create a new matrix by squaring every element of the given matrix:
> apply(m,c(1,2),function(x) x^2) 
 
     [,1] [,2] [,3] [,4] 
[1,]    1   25   81  169 
[2,]    4   36  100  196 
[3,]    9   49  121  225 
[4,]   16   64  144  256 
  1. Apply a function to every row and pass an argument to the function:
> apply(m, 1, quantile, probs=c(.4,.8)) 
    [,1] [,2] [,3] [,4] 
40%  5.8  6.8  7.8  8.8 
80% 10.6 11.6 12.6 13.6 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required