简体   繁体   中英

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?

To iterate over the functions and paramVector objects at the same time, use Map. For example

Map(function(f,p) f(p), functions, paramVector)

Note that Map() always returns a list. You can also use mapply() which will attempt to simplify to a vector

mapply(function(f,p) f(p), functions, paramVector)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM