The apply, lapply, sapply, and tapply functions

R has some very handy functions such as apply, sapply, tapply, and mapply, that can be used to reduce the task of writing complicated statements. Also, using them makes our code look cleaner. The apply() function is similar to writing a loop statement.

The lapply() function is very similar to the apply() function but can be used on lists; this will return a list. The sapply() function is very similar to lapply() but returns a vector and not a list.

How to do it…

The apply() function can be used as follows:

mat= matrix(1:25, 5,5)
apply(mat,1,sd)

The lapply() function can be used in the following way:

j = list(x = 1:4, b = rnorm(100,1,2))
lapply(j,mean)

The tapply() function is useful when we have broken ...

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.