Loop Functions

lapply

Loop over a list and apply a function.

Let's calculate mean of each element in the list using mean function.

list <- list(a = 1:10, b = 10:100)

lapply(list, mean)

Using runif function.

lapply(1:10, runif, min = 0, max = 10)

sapply

sapply is almost the same as lapply but it tries to simplify the result if possible.

  • If the result is a list, it returns vector

  • If the result is list where each element is vector, matrix is returned

  • If it does not know, list is returned

Let's see what is the difference between lapply and sapply.

> lapply(list, mean)
$a
[1] 5.5

$b
[1] 55

> sapply(list,mean)
   a    b
 5.5 55.0

apply

Evaluate

  • X - is array

  • MARGIN - margin to retain

  • FUN - function

  • ... - argumetns for FUN function

We can use rowSums, rowMeans, colSums and colMeans functions instead, they are faster.

mapply

With mapply function we can iterate trough multiple sets. E.g.

tapply

Applies function across subset of a vector. It splits data into little pieces and after calculation it is put together again.

First we create a sample data.

Mean of each number in x.

Turn of simplify and function returns list then.

Last updated

Was this helpful?