Applying Functions to Lists
In R, functions can be applied to lists in various ways using functions like lapply(), sapply() and Map().
lapply() function
The lapply() function applies a function to each element of a list and returns a list.
Syntax:
lapply(list, function)
Example:
> my_list <- list(1:3, 4:6, 7:9)
> res_ls <- lapply(my_list, sum)
> print(res_ls)
Output:
[[1]]
[1] 6
[[2]]
[1] 15
[[3]]
[1] 24
> class(res_ls)
Output:
[1] "list"
sapply() function
The sapply() function is similar to lapply(), but it simplifies the output to a vector or matrix if possible.
Syntax:
sapply(list, function)
Example:
> my_list <- list(1:3, 4:6, 7:9)
> result <- sapply(my_list, sum)
> print(result)
Output:
[1] 6 15 24
> class(result)
Output:
[1] "integer"
Map() function
The Map() function applies a function to multiple lists at the same time.
Syntax:
Map(function, list1, list2)
Example:
> list1 <- list(a = 1:3, b = 4:6)
> list2 <- list(c = 7:9, d = 10:12)
> result <- Map(`+`, list1, list2)
> print(result)
Output:
$a
[1] 8 10 12
$b
[1] 14 16 18
Note: Map() adds the first elements of the two lists together, then the second elements, and so on. The result takes its names (a and b) from the first list.