在 R 编程中同时对多个列表执行操作 – mapply()函数
R 语言中的mapply()函数代表多变量应用,用于同时对多个列表执行数学运算。
Syntax: mapply(func, list1, list2, …)
Parameters:
- list1, list2, …: Created Lists
- func: operation to be applied
R语言示例中的mapply()函数
示例 1:在 R 中使用 mapply()函数对两个列表求和
R
# R program to illustrate
# mapply() function
# Creating a list
A = list(c(1, 2, 3, 4))
# Creating another list
B = list(c(2, 5, 1, 6))
# Applying mapply()
result = mapply(sum, A, B)
print(result)
R
# R program to illustrate
# mapply() function
# Creating a list
A = list(c(1, 2, 3, 4))
# Creating another list
B = list(c(2, 5, 1, 6))
# Applying mapply()
result = mapply(prod, A, B)
print(result)
R
Data1 <- c(1,2,3)
Data2 <- c(10,20,30)
mult_one<-function(Data1,Data2)
{
Data1+Data2
}
mapply(mult_one,Data1,Data2)
输出:
[1] 24
示例 2:在 R 中使用 mapply()函数的两个列表的乘积
R
# R program to illustrate
# mapply() function
# Creating a list
A = list(c(1, 2, 3, 4))
# Creating another list
B = list(c(2, 5, 1, 6))
# Applying mapply()
result = mapply(prod, A, B)
print(result)
输出:
[1] 1440
示例 3:具有多个参数的 mapply()函数
R
Data1 <- c(1,2,3)
Data2 <- c(10,20,30)
mult_one<-function(Data1,Data2)
{
Data1+Data2
}
mapply(mult_one,Data1,Data2)
输出:
11 22 33