Skip to content
Prev 365976 / 398502 Next

"Safe" use of iterator (package iterators)

That is a helpful, and important, caveat. So, perhaps I should amend my original question to ask something like is it safe *when* length(r1) == length(r2)

-----Original Message-----
From: David Winsemius [mailto:dwinsemius at comcast.net] 
Sent: Friday, December 09, 2016 1:27 PM
To: Doran, Harold <HDoran at air.org>
Cc: r-help at r-project.org
Subject: Re: [R] "Safe" use of iterator (package iterators)
I wasn't sure how this would or should behave. I'm not an experienced user, merely a reader of help pages. Neither the help page, not the vignette references on the help page answered my questions in this case. I expected that call would behave analogously to the behavior of mapply when given iterators of unequal length. (The shorter of the objects is recycled to reach the length of the longer object.) That expectation was not realized. It appears that the length of first object of the objects determines computation length, but that missing values will not be recycled for the shorter iterator. An error is not reported, but rather numeric(0) is returned. So in one sense the %dopar% version is "safer" at least to the extent of not failing with an error that would have occurred when using a for-loop.

This was my test case:

r1 <- vector("list", 10)
for(i in 1:20){
	r1[[i]] <-20:29+i*10
# random numbers are not good for determining sequences of operations }
r2 <- vector("list", 20)
for(i in 1:10){
	r2[[i]] <- 1:10 +i
}
itx1 <- iter(r1)
itx2 <- iter(r2)

result2 <- foreach(i = itx1, j = itx2) %dopar% {
	i + j
	}	

result2