Reputation: 1667
I was reading the documentation of the foreach
package in r and was able to understand how .combine
is done on c
, rbind
and cbind
. But the documentation says that you can also pass the name of a function to the .combine
in the statement if you want to combine using this function. I'm not able to understand the output when trying to access the individual elements of each foreach inside this function that I'm combining on. (Let me call this function as mycombinefunc
)
This is what I have tried. I don't understand why the output is printed twice in the output of the foreach statement.
> mycombinefunc= function(...){mylist = list(...);print(mylist)}
> foreach(i=1:2, .combine='mycombinefunc') %do% {c(1:5)}
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 1 2 3 4 5
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 1 2 3 4 5
#just calling the function directly to show what the expected output for one iteration of the foreach loop looks like. I would have expected that the above function call would produce two copies of the below output
> mycombinefunc(c(1:5))
[[1]]
[1] 1 2 3 4 5
Upvotes: 1
Views: 1739
Reputation: 206197
The combine function is run to merge a new result to the previous results. With your example, you're seeing the output twice because you explicitly have a print() statement in your combine function so you see the two vectors that are being passed to your combine function. Then, this value is returned from the foreach() and by default R will print the result of that function to the console.
You should expect your combine
to recieve two values. One from the previous iteration and the current iteration. So what's really getting called is
mycombinefunc(1:5, 1:5)
and you're expected to "combine" this into a single result. This is very similar to how the Reduce()
function in R works. Maybe checkout the ?Reduce
help page for more info.
Let's say you wanted a combine function that would just add up the vectors, you could do
mycombinefunc= function(a,b){a+b}
foreach(i=1:3, .combine='mycombinefunc') %do% {c(1:5)}
# [1] 3 6 9 12 15
Notice how we get one result returned from foreach()
. We don't see any intermediate values because we removed the print()
from the combine function. Also, we get a single vector rather than a list because we choose to add the elements together rather than appending to a list.
Upvotes: 3