lapply in R

The lapply() function does the following simple series of operations:

  1. It loops over a list, iterating over each element in that list
  2. It applies a function to each element of the list (a function that you specify)
  3. and returns a list.

To get the help file type the following code.

?lapply()

The body of the lapply() function can be seen here by just typing lapply in your console.

 

lapply

Output:

function (X, FUN, …)
{
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X))
X <- as.list(X)
.Internal(lapply(X, FUN))
}
<bytecode: 0x0000000003e6df80>
<environment: namespace:base>

Example:

 

x <- list(a = 1:10, b = rep(10,10), c = rnorm(10))
x
lapply(x, sum)

Output:

> x
$a
[1] 1 2 3 4 5 6 7 8 9 10

$b
[1] 10 10 10 10 10 10 10 10 10 10

$c
[1] 0.22871841 1.27507641 1.28141494 1.64109627 1.66544463 2.46437516 -0.44645609
[8] 0.02727229 0.08409925 1.62737229

> lapply(x, sum)
$a
[1] 55

$b
[1] 100

$c
[1] 9.848414

Example 2:

 

x <- 1:5
lapply(x, runif, min = 0, max = 5)

Output:

[[1]]
[1] 4.798667

[[2]]
[1] 1.872322 1.182642

[[3]]
[1] 1.856415 2.575359 4.694854

[[4]]
[1] 2.066576 3.152852 3.789368 2.106707

[[5]]
[1] 2.76430044 0.44468126 3.38272729 3.48570913 0.04339449

Example 3:

 

x <- list(a = matrix(1:9, 3, 3), b = matrix(1:4, 2, 2), c=matrix(1:20,4,5))
x
lapply(x,t)

Output:

> x
$a
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

$b
[,1] [,2]
[1,] 1 3
[2,] 2 4

$c
[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20

> lapply(x,t)
$a
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9

$b
[,1] [,2]
[1,] 1 2
[2,] 3 4

$c
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
[5,] 17 18 19 20

Loop Functions

sapply