[英]R - how do I run each function in a list of functions with parameters given by a vector
Suppose I have a list of functions and a vector of parameter values: 假设我有一个函数列表和一个参数值向量:
functions <- list(a = function(x) x *2, b = function(x) x*3, c = function(x) x * 4)
paramVector <- c(2, 2, 1)
Now I want the following functionality of calling each function with the corresponding parameter and collating the result into a vector: 现在,我需要以下功能,即使用相应的参数调用每个函数并将结果整理为向量:
result <- c()
for (idx in 1:length(functions)) {
result[idx] <- functions[[idx]](paramVector[idx])
}
result
Is there a way to do this without the for loop? 没有for循环,有没有办法做到这一点?
To iterate over the functions
and paramVector
objects at the same time, use Map. 要同时遍历functions
和paramVector
对象,请使用Map。 For example 例如
Map(function(f,p) f(p), functions, paramVector)
Note that Map()
always returns a list. 注意, Map()
总是返回一个列表。 You can also use mapply()
which will attempt to simplify to a vector 您还可以使用mapply()
尝试将其简化为向量
mapply(function(f,p) f(p), functions, paramVector)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.