Is it possible to have zip iterator (i.e. "zip" two iterators together) in foreach?
foreach, iterator, r
Solution
There is an `izip` function in the `itertools` package that does what you describe:
library(itertools)
out <- foreach(x=izip(iter1, iter2)) %do% {
# x[[1]] contains a value from iter1
# x[[2]] contains a value from iter2
}
But I prefer to specify multiple loop variables to `foreach`:
out <- foreach(x=iter1, y=iter2) %do% {
# x contains a value from iter1
# y contains a value from iter2
}
Both solutions iterate over values from the iterators in parallel. If you want the two arguments in a list, then `izip` is more convenient.
Problem
I have two objects of equal length (one is a list produced by parsing JSON, and another is a slice of multi-dimensional of an array), e.g.: ``` library(rjson) library(foreach) iter1<-iter( fromJSON(file=jsonfilename)$someJSONarray ) iter2<-iter( myarr, by="row" ) ``` I need to be able to do the following: ``` out=foreach(x=zipiter(iter1,iter2),combine=list) %do% { #Do stuff with elements from both iterators accessed by e.g. x[[1]] and x[[2]] } ``` Is there any standard way of doing it (like in Python/C++ with boost Zip iterator)?