10

How to avoid "could not find function "%dopar%"" in a function of a package when only imports (not depends) foreach in DESCRIPTION of a package? is there a way like foreach::%dopar% as I use foreach::foreach in function? Thank you.

Code like:

In function

foreach::foreach(1:9) %dopar% {

...}

In DESCRIPTION

Imports: 
    Matrix,
    parallel,
    foreach,
   doParallel
Zhilong Jia
  • 2,329
  • 1
  • 22
  • 34

3 Answers3

12

The following worked for me. Define a local %do% or %dopar% as follows

`%dopar%` <- foreach::`%dopar%`
`%do%` <- foreach::`%do%`

Then you should be able to run

foreach::foreach(i = 1:9, .combine = "+") %dopar% {i}
foreach::foreach(i = 1:9, .combine = "+") %do% {i}
rwolst
  • 12,904
  • 16
  • 54
  • 75
7

You need to use backticks: foreach::`%dopar%` (or quotes foreach::"%dopar%" will also work).

konvas
  • 14,126
  • 2
  • 40
  • 46
  • 1
    Could you clarify a bit more on how to explicitly call %dopar%? I'm trying to run the following which doesn't work. `foreach::foreach(i = 1:9, .combine = "+") foreach::\`%dopar%\` {i}` and i've tried various combination with the backticks, but it usually gives an "unexpected symbol" error. Thanks! – Kevin Zen Sep 09 '16 at 16:30
  • @KevinZen I am not sure how to reproduce this error, and I don't recall ever getting it. Do you get the same if you use quotes? What about defining an alias like `\`%dopar%\` <- foreach::\`%dopar%\`` and then just use that? – konvas Sep 12 '16 at 19:48
  • 1
    Yeah, if I try and define this function explicitly without using Roxygen2 neither backticks nor quotes work. I realized that I didn't need to worry about `foreach::%dopar%` when using Roxygen2. It worked fine with just `import(foreach)` – Kevin Zen Sep 16 '16 at 14:55
4

@Kevin Zen,

I was having the same issue, but I think I just resolved it by using the "importFrom" field in the namespace file. I use Roxygen2 to document, so I simply included the tag:

#' @importFrom foreach %dopar%

with the function foreach is called in. It created a field in the namespace file like such:

importFrom(foreach,"%dopar%")

so if you aren't using Roxygen2, you could just put that line in your namespace and that should do the trick as well.

That should prevent the cran check from complaining. However, once you try to run the code on a computer that doesn't already have the "foreach" package loaded and attached via:

library(foreach)

you will get a message that %dopar% is not found if "foreach" is listed under "Imports" rather than "Depends" in your DESCRIPTION file. So make sure foreach is listed in the "Depends" field.

Drwhit
  • 89
  • 1
  • 7