Examples for 'base::lapply'


Apply a Function over a List or Vector

Aliases: lapply sapply vapply replicate simplify2array

Keywords: iteration list

### ** Examples

require(stats); require(graphics)

x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
# compute the list mean for each list element
lapply(x, mean)
$a
[1] 5.5

$beta
[1] 4.535125

$logic
[1] 0.5
# median and quartiles for each list element
lapply(x, quantile, probs = 1:3/4)
$a
 25%  50%  75% 
3.25 5.50 7.75 

$beta
      25%       50%       75% 
0.2516074 1.0000000 5.0536690 

$logic
25% 50% 75% 
0.0 0.5 1.0 
sapply(x, quantile)
         a        beta logic
0%    1.00  0.04978707   0.0
25%   3.25  0.25160736   0.0
50%   5.50  1.00000000   0.5
75%   7.75  5.05366896   1.0
100% 10.00 20.08553692   1.0
i39 <- sapply(3:9, seq) # list of vectors
sapply(i39, fivenum)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]  1.0  1.0    1  1.0  1.0  1.0    1
[2,]  1.5  1.5    2  2.0  2.5  2.5    3
[3,]  2.0  2.5    3  3.5  4.0  4.5    5
[4,]  2.5  3.5    4  5.0  5.5  6.5    7
[5,]  3.0  4.0    5  6.0  7.0  8.0    9
vapply(i39, fivenum,
       c(Min. = 0, "1st Qu." = 0, Median = 0, "3rd Qu." = 0, Max. = 0))
        [,1] [,2] [,3] [,4] [,5] [,6] [,7]
Min.     1.0  1.0    1  1.0  1.0  1.0    1
1st Qu.  1.5  1.5    2  2.0  2.5  2.5    3
Median   2.0  2.5    3  3.5  4.0  4.5    5
3rd Qu.  2.5  3.5    4  5.0  5.5  6.5    7
Max.     3.0  4.0    5  6.0  7.0  8.0    9
## sapply(*, "array") -- artificial example
(v <- structure(10*(5:8), names = LETTERS[1:4]))
 A  B  C  D 
50 60 70 80 
f2 <- function(x, y) outer(rep(x, length.out = 3), y)
(a2 <- sapply(v, f2, y = 2*(1:5), simplify = "array"))
, , A

     [,1] [,2] [,3] [,4] [,5]
[1,]  100  200  300  400  500
[2,]  100  200  300  400  500
[3,]  100  200  300  400  500

, , B

     [,1] [,2] [,3] [,4] [,5]
[1,]  120  240  360  480  600
[2,]  120  240  360  480  600
[3,]  120  240  360  480  600

, , C

     [,1] [,2] [,3] [,4] [,5]
[1,]  140  280  420  560  700
[2,]  140  280  420  560  700
[3,]  140  280  420  560  700

, , D

     [,1] [,2] [,3] [,4] [,5]
[1,]  160  320  480  640  800
[2,]  160  320  480  640  800
[3,]  160  320  480  640  800
a.2 <- vapply(v, f2, outer(1:3, 1:5), y = 2*(1:5))
stopifnot(dim(a2) == c(3,5,4), all.equal(a2, a.2),
          identical(dimnames(a2), list(NULL,NULL,LETTERS[1:4])))

hist(replicate(100, mean(rexp(10))))
plot of chunk example-base-lapply-1
## use of replicate() with parameters:
foo <- function(x = 1, y = 2) c(x, y)
# does not work: bar <- function(n, ...) replicate(n, foo(...))
bar <- function(n, x) replicate(n, foo(x = x))
bar(5, x = 3)
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    3    3    3
[2,]    2    2    2    2    2

[Package base version 4.2.3 Index]