The apply function

The apply function is useful for doing row-by-row or column-by-column calculations in a matrix. It also extends to higher dimensional arrays. Let's look at some examples.

In the following R code, we define a matrix, x, with 4 rows and 3 columns, containing the integers 1, 2, ..., 12. Then we use apply to calculate various things. You should print out x to see that is has in it what you think it does. Then try out the R code to figure out how apply works.

x <- matrix(1:12,ncol=3,nrow=4) # create matrix x
x # print it out
apply(x,1,sum)
apply(x,2,sum)
apply(x,1,mean)
apply(x,2,mean)
apply(x,1,var)
apply(x,1,function(y) mean(y)^2) # defined function within apply