3

I just studied the foreach function in the R, and saw the codes:

x <- foreach(i=1:3 ) %do% exp(i)

I am just curious how can we use "%do%" in the function foreach. What is the "%do%" for the function foreach? Is it a kind of special parameter?

I've seen the source code of foreach, but cannot find any clue.

So anyone can help me to figure what is it, and how to use it in our defined functions.

Note to moderators: The function %do% has a specific purpose that is not entirely explained by the fact that the flanking percent signs make it an infix operators. Please reopen.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
Colin Ji
  • 803
  • 7
  • 15
  • 1
    Aside from the fact that the %do% is defined as an infix function, the nominated duplicate doesn't really answer what I think is being asked. – IRTFM Dec 17 '15 at 02:15
  • It appears some moderator decided it. Not the first time that I disagreed with a moderator. – IRTFM Dec 17 '15 at 02:20

1 Answers1

3

The %do% is a function. You can even see its code (assuming you have the package foreach installed) by typing:

foreach::`%do%`

It takes two arguments: the first is a foreach-object which establishes the iterations; the second is the expression that follows the %do% when it is used in the infix mode.

function (obj, ex) 
{
    e <- getDoSeq()
    e$fun(obj, substitute(ex), parent.frame(), e$data)
}

Apparently the construction of a foreach object includes a 'fun' object, which is extracted by getDoSeq. You can actually see where this is if you execute this code:

z <- foreach::foreach(i=1:3)
str(z)

It further appears that one can have either a seqFun presumably supplied by the user or if one is not supplied then the foreach:::doSEQ function will be used to drive the itteration. So the answer is not to the question: "how can we use %do%?", but should rather be in response to the question: "how does %do% process the foreach-object and successively evaluate the supplied expression in the joint context of the iteration variables and the parent environment".

IRTFM
  • 258,963
  • 21
  • 364
  • 487