R mapply() Function - Multivariate Application

R 语言实例R Language Examples

The R mapply() function is a multivariate version of sapply(), which can apply a function to multiple lists/vectors simultaneously.

When you need to process multiple arguments element by element, mapply() can replace nested loops.

The syntax of the mapply() function is as follows:

mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE)

Parameter description:

  • FUNThe function to be applied.

  • ...Multiple arguments (lists or vectors) to pass to FUN.

  • MoreArgsA list of fixed arguments (not participating in element-wise iteration).

Examples

# Generate sequences with mapply
result <- mapply(seq, from = c(1, 10, 100),
                      to = c(3, 15, 105))
print("Generated sequences:")
print(result)

# Process multiple arguments element by element
names <- c("Zhang San", "Li Si", "Wang Wu")
math <- c(88, 92, 76)
english <- c(90, 88, 82)

# Calculate the total score of each student
total <- mapply(function(n, m, e) {
  paste(n, "Total score:", m + e)
}, names, math, english)
print("Each person's total score:")
print(total)

Executing the above code produces the following output:

[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 语言实例R Language Examples

Other Extensions