Using `lapply`, `sapply` and `vapply` in r
Using `lapply`, `sapply` and `vapply` in r
Example 1: a list contains one vector
1
2
3
4
x1 <- list(c(1, 2, 3))
lapply_x1 <- lapply(x1, median)
sapply_x1 <- sapply(x1, median)
vapply_x1 <- vapply(x1, median, numeric(1))
1
2
3
lapply_x1 is 2 in list class
sapply_x1 is 2 in numeric class
vapply_x1 is 2 in numeric class
Example 2: a list contains two vectors with same length
1
2
3
4
x2 <- list(c(1, 2, 3), c(4, 5, 6))
lapply_x2 <- lapply(x2, median)
sapply_x2 <- sapply(x2, median)
vapply_x2 <- vapply(x2, median, numeric(1))
1
2
3
4
5
6
7
8
9
10
11
12
lapply_x2 in list class
[[1]]
[1] 2
[[2]]
[1] 5
sapply_x2 in numeric class
[1] 2 5
vapply_x2 in numeric class
[1] 2 5
Example 3: a list contains two vectors with different and same length
1
2
3
4
x3 <- list(c(1, 2, 3), c(4, 5, 6, 7))
square_function <- function(x) x^2
lapply_x3 <- lapply(x3, square_function)
sapply_x3 <- sapply(x3, square_function)
1
2
3
4
5
6
7
8
9
10
11
12
13
lapply_x3 in list class
[[1]]
[1] 1 4 9
[[2]]
[1] 16 25 36 49
sapply_x3 in list class
[[1]]
[1] 1 4 9
[[2]]
[1] 16 25 36 49
1
vapply(x3, square_function, numeric(3))
1
2
Error in vapply(x3, square_function, numeric(3)): values must be length 3,
but FUN(X[[2]]) result is length 4
1
2
x3_same_length <- list(c(1, 2, 3), c(4, 5, 6))
vapply_x3_same_length <- vapply(x3_same_length, square_function, numeric(3))
1
2
3
4
5
6
7
class(vapply_x3_same_length)
[1] "matrix" "array"
vapply_x3_same_length
[,1] [,2]
[1,] 1 16
[2,] 4 25
[3,] 9 36
Summary for lapply
, sapply
and vapply
lapply |
sapply |
vapply |
|
---|---|---|---|
Return | list | vector / matrix / array / list | pre-specified type |
References:
RDocumentation lapply: Apply a Function over a List or Vector