Objective
- Creation of Example Data
- Example 1: apply() Function
- Example 2: lapply() Function
- Example 3: sapply() Function
- Example 4: vapply() Function
- Example 5: tapply() Function
- Example 6: mapply() Function
Creation of Example Data
my_data <- data.frame(x1 = 1:5,
x2 = 2:6,
x3 = 3)
my_data
## x1 x2 x3
## 1 1 2 3
## 2 2 3 3
## 3 3 4 3
## 4 4 5 3
## 5 5 6 3
my_list <- list(1:5,
letters[1:3],
777)
my_list
## [[1]]
## [1] 1 2 3 4 5
##
## [[2]]
## [1] "a" "b" "c"
##
## [[3]]
## [1] 777
apply() function
apply(my_data, 1, sum) # 1 indicates that we are using apply by row
## [1] 6 8 10 12 14
apply(my_data, 2, sum) # 2 indicates that we are using apply by column
## x1 x2 x3
## 15 20 15
lapply() function
## [[1]]
## [1] 5
##
## [[2]]
## [1] 3
##
## [[3]]
## [1] 1
## [1] 5 3 1
vapply(my_list, length, integer(1))
## [1] 5 3 1
tapply() function
input_values <- 1:10
input_values
## [1] 1 2 3 4 5 6 7 8 9 10
input_factor <- rep(letters[1:5], 2)
input_factor
## [1] "a" "b" "c" "d" "e" "a" "b" "c" "d" "e"
tapply(input_values, input_factor, sum)
## a b c d e
## 7 9 11 13 15
mapply() function
mapply(rep, times = 1:5, letters[1:5])
## [[1]]
## [1] "a"
##
## [[2]]
## [1] "b" "b"
##
## [[3]]
## [1] "c" "c" "c"
##
## [[4]]
## [1] "d" "d" "d" "d"
##
## [[5]]
## [1] "e" "e" "e" "e" "e"