Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R mapply() Function - Applying a Function to Multiple Variables

R mapply() Function - Applying a Function to Multiple Variables

R Language Examples R Language Examples

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:

Example

Generate a sequence with mapply

result

<-

mapply

(

seq

, from

=

c

(

1

,

10

,

100

)

,

                      to

=

c

(

3

,

15

,

105

)

)

print

(

"Generated sequence:"

)

print

(

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

)

print

(

"Total score per person:"

)

print

(

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 R Language Examples