R: It is impossible to find a “function” when passing ... to the foot?

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#37 1 papply(1:5, function(i, x) { return(data.frame(a = i, b = i + x)) }, x = 1) 

I do not know why this error occurs. How can I resolve the error and make the function work?

+3
source share
1 answer

It comes down to the problem of comparing positions and arguments.

x is a formal argument papply , so when you call it in

 papply(1:5,function(i,x){return(data.frame(a=i,b=i+x))},x=1) 

This means that 1:5 matches as fun → therefore, an error.

In the current form of your function, it is impossible for R to know that when you denote x=1 , what do you want this to be considered in the component ...

See the MoreArgs argument in mapply for an approach that might be useful.

+4
source

Source: https://habr.com/ru/post/1245107/


All Articles