SkyWalker
SkyWalker

Reputation: 14309

What's the correct way to implement a user-defined do.call's what function?

I have a do.call use-case (as result of calling mclapply) simplified to the following:

myfunc <- function(x, y) {
  str(x)
  #return(x + y)
} 

res <- list(list(x=1,y=1),list(x=2,y=2),list(x=3,y=3))
str(res)

do.call(what="myfunc", res)

No matter what I do in myfunc it never works. I'd expect do.call to call myfunc three times and pass the resp. x and y but instead it calls it once with all the data and complains it doesn't know what to do with the remaining arguments ... what's the correct way to implement the what function such that will apply something over each list element as it does with any other base function?

UPDATE What lead to my confusion over the use of do.call is that I always saw its use to "reduce" the results of a collection. What I didn't realize is that the functions being called by do.call do handle list types and reduce scenarios e.g. rbind

Upvotes: 2

Views: 136

Answers (2)

akrun
akrun

Reputation: 886978

In tidyverse, walk + reduce can use used

library(purrr)
walk(res, reduce, myfunc)
#num 1
#num 2
#num 3

Upvotes: 1

SmokeyShakers
SmokeyShakers

Reputation: 3412

lapply handles the looping, do.call applies list elements as arguments. Try this:

lapply(res, function(l) do.call('myfunc', l))

Upvotes: 4

Related Questions