I want to implement another version of the lapply
function, which allows me to specify whether to run in parallel. The code looks like this:
papply <- function(x,fun,..., parallel=FALSE,parallel.options=list(mode="socket",cpus=2), integrate=rbind,convert=NULL) { if(parallel) { require(parallelMap) do.call(parallelStart,parallel.options) result <- parallelLapply(x,fun,...) parallelStop() } else { result <- lapply(x,fun,...) } if(is.function(integrate)) { result <- do.call(integrate,result) } if(is.function(convert)) { result <- convert(result) } return(result) }
If parallel=TRUE
, I use parallelLapply()
in the {parallelMap}
package, otherwise I use the regular lapply
function. In both methods, the vector / list I'm trying to display is x
, and the display function is fun
. Since fun
can have more than one parameter, I use ...
to pass extra arguments to fun
.
However, if additional arguments are not specified, for example
papply(1:5,function(i,x){return(data.frame(a=i,b=i+1))})
It works fine and returns the correct values:
ab 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6
But if additional arguments are specified, for example
papply(1:5,function(i,x){return(data.frame(a=i,b=i+x))},x=1)
It does not work, but reports an error, for example
Error in get(as.character(FUN), mode = "function", envir = envir) : object 'fun' of mode 'function' was not found 4 get(as.character(FUN), mode = "function", envir = envir) 3 match.fun(FUN) 2 lapply(x, fun, ... = ...) at utils.R
I do not know why this error occurs. How can I resolve the error and make the function work?