当前位置: 动力学知识库 > 问答 > 编程问答 >

How to pass function arguments when creating a list of tasks in R?

问题描述:

I'm trying to create a list of tasks to run in R parallel using mclapply.

library(parallel)

tasks <- list(

job1 = y(5),

job2 = y(6)

)

# Using fork()

out <- mclapply(

tasks,

function(f) f(),

mc.cores = length(tasks)

)

where y is for example:

y<-function(x){

a<-x^2

return(a)

}

When creating the list, it executes the functions with arguments instead of only storing it as a list. (So this is before even arriving at the actual mclapply.)

If I use a function y without any arguments, this approach runs fine:

tasks <- list(

job1 = y,

job2 = y

)

# Using fork()

out <- mclapply(

tasks,

function(f) f(),

mc.cores = length(tasks)

)

where y is for example:

y<-function(){

a<-5^2

return(a)

}

So how do I store the functions with arguments in a list without executing the functions (until I tell them to in mclapply)?

网友答案:

Try these steps:

tasks <- list(
    job1 <- substitute(y(5)),
    job2 <- substitute(y(6))
)

And then

out <- mclapply( 
    tasks,
    FUN=function(x) eval(x)), 
    mc.cores = length(tasks)
)

This should work with parallel operations, but it is impossible for me to test it since I'm using Windows.

分享给朋友:
您可能感兴趣的文章:
随机阅读: