R lapply() Function - Applying a Function to a List
The R lapply() function is used to apply a function to each element of a list or vector, returning a list.
lapply() is one of the most important functional programming tools in R, avoiding the use of for loops.
The syntax of the lapply() function is as follows:
lapply(X, FUN, ...)
Parameter Description:
-
X The input list or vector.
-
FUN The function to apply.
-
... Extra arguments passed to FUN.
Example
Compute the mean for each element of the list
list_data
<-
list
(
group1
=
c
(
85
,
88
,
90
,
87
,
92
)
,
group2
=
c
(
72
,
75
,
78
,
70
,
76
)
,
group3
=
c
(
90
,
93
,
88
,
95
,
91
)
)
result
<-
lapply
(
list_data,
mean
)
(
"Means of each group:"
)
(
result
)
Compute the range for each column of a data frame
df
<-
data.frame
(
Math
=
c
(
88
,
92
,
76
)
,
English
=
c
(
90
,
88
,
82
)
,
Programming
=
c
(
85
,
91
,
78
)
)
result2
<-
lapply
(
df
,
range
)
(
"Ranges of each column:"
)
(
result2
)
The output of the code above is:
[1] "各组的均值:"
$group1
[1] 88.4
$group2
[1] 74.2
$group3
[1] 91.4
[1] "各列的范围:"
$数学
[1] 76 92
$英语
[1] 82 90
$编程
[1] 78 91
R Language Examples