R mapply() Function - Applying a Function to Multiple Variables
The R mapply() function is the multivariate version of sapply(), able to apply a function to multiple lists/vectors simultaneously.
When you need to process multiple arguments element-wise, mapply() can replace nested loops.
The syntax of the mapply() function is as follows:
mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE)
Parameter Description:
-
FUN The function to apply.
-
... Multiple arguments to pass to FUN (lists or vectors).
-
MoreArgs A list of fixed arguments (not involved in element-wise iteration).
Example
Generate a sequence with mapply
result
<-
mapply
(
seq
, from
=
c
(
1
,
10
,
100
)
,
to
=
c
(
3
,
15
,
105
)
)
(
"Generated sequence:"
)
(
result
)
Process multiple arguments element-wise
names
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
)
math
<-
c
(
88
,
92
,
76
)
english
<-
c
(
90
,
88
,
82
)
Compute the total score for each student
total
<-
mapply
(
function
(
n, m, e
)
{
paste
(
n,
"Total score:"
, m
e
)
}
,
names
, math, english
)
(
"Total score per person:"
)
(
total
)
The output of the code above is:
[1] "生成的序列:"
[[1]]
[1] 1 2 3
[[2]]
[1] 10 11 12 13 14 15
[[3]]
[1] 100 101 102 103 104 105
[1] "每人总分:"
[1] "张三 总分: 178" "李四 总分: 180" "王五 总分: 158"
R Language Examples