Source

You can find relevant information form the following Stack Overflow thread

Preparation

Create a list of lists in which has one vector of integer

# The following assigment is doing the same thing
# my_list <- list(c(1:3), c(4:6), c(7:9))
my_list <- list(1:3, 4:6, 7:9)

Define a custom function

my_func <- function(x) {
  x * x
}

Now try the two functions on the list

lapply(my_list, my_func)
## [[1]]
## [1] 1 4 9
## 
## [[2]]
## [1] 16 25 36
## 
## [[3]]
## [1] 49 64 81
# The first do.call does not work as my_func expects one argument and my_list provides three instead
do.call(my_func, my_list)
## Error in (function (x) : unused arguments (4:6, 7:9)
# The following call works fine as we extracted the first list of my_list
do.call(my_func, my_list[1])
## [1] 1 4 9

We’ll try aggregate function on the list

lapply(my_list, mean, na.rm = TRUE)
## [[1]]
## [1] 2
## 
## [[2]]
## [1] 5
## 
## [[3]]
## [1] 8
# The do.call does not work as mean function expects second argument 'trim' as numeric and my_list provide a list for it
do.call(mean, my_list)
## Warning in if (na.rm) x <- x[!is.na(x)]: the condition has length > 1 and
## only the first element will be used
## Error in mean.default(1:3, 4:6, 7:9): 'trim' must be numeric of length one
# The following lapply call will do nonsense because each element is binded to nothing. So my_list become a list of lists in which there is a dataframe
lapply(my_list, rbind)
## [[1]]
##      [,1] [,2] [,3]
## [1,]    1    2    3
## 
## [[2]]
##      [,1] [,2] [,3]
## [1,]    4    5    6
## 
## [[3]]
##      [,1] [,2] [,3]
## [1,]    7    8    9
# The do.call works just fine
do.call(rbind, my_list)
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9

Combine lapply and do.call to make a simpler structure (in this case a character vector) from a list

x <- lapply(iris, class)
do.call(c,x)
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
##    "numeric"    "numeric"    "numeric"    "numeric"     "factor"

Thank you

I hope you like the 2 Mins of R. I’ll see you in the next one!