1 Objective

  1. Creation of Example Data
  2. Example 1: apply() Function
  3. Example 2: lapply() Function
  4. Example 3: sapply() Function
  5. Example 4: vapply() Function
  6. Example 5: tapply() Function
  7. Example 6: mapply() Function

2 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

3 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

4 lapply() function

lapply(my_list, length)
## [[1]]
## [1] 5
## 
## [[2]]
## [1] 3
## 
## [[3]]
## [1] 1
sapply(my_list, length)
## [1] 5 3 1
vapply(my_list, length, integer(1))
## [1] 5 3 1

5 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

6 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"