Friday 24 July 2015

R: lapply and sapply

Lapply
Loop over a list and evaluate a function on each element. It returns a list.

Syntax
lapply(X, FUN, ...)

 X is a list (or) an object.

FUN : Function to be applied on each element of X.


… : Optional arguments to function FUN.
> x <- list(a=c(1:10), b=c(5:15))
> lapply(x, mean)
$a
[1] 5.5

$b
[1] 10


In the above snippet, lapply performs mean operation on every element of the list.
> x <- c(1,2,3,4,5)
> lapply(x, runif, min=0, max=10)
[[1]]
[1] 6.026284

[[2]]
[1] 5.995836 1.120055

[[3]]
[1] 4.5203892 0.6333992 6.5279867

[[4]]
[1] 7.404317 6.844588 1.381577 1.235436

[[5]]
[1] 9.515179 5.358644 3.994463 4.044702 8.319785

“runif” generates random numbers between min and max.
For input 1, runif generates 1 random number.
For input 2, runif generates 2 random numbers.
For input 3, runif generates 3 random numbers.
For input 4, runif generates 4 random numbers.
For input 5, runif generates 5 random numbers.

sapply
“sapply” is a user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = "array", an array if appropriate.

If the result is a list, where every element of length 1, then a vector is returned
If the result is a list, where every element of length >1, then a matrix is returned

If it is unable to process as vector (or) matrix, simply a list is returned.
> x <- list(a=c(1:10), b=c(5:15))
> 
> x <- list(a1=c(1:5), a2=c(5:10), a3=c(10:15))
> lapply(x, mean)
$a1
[1] 3

$a2
[1] 7.5

$a3
[1] 12.5

> 
> sapply(x, mean)
  a1   a2   a3 
 3.0  7.5 12.5



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment