I have a list like {{a,x},{b,y},{c,x},{d,z},{e,y}}
and would like to produce from it a list formed by collecting all top-level elements whose second components are the same into a single list. For the list above, the desired output would be { {{a,c},x}, {{b,e},y}, {d, z}}
. Here x
, y
, and z
could also be lists, if that matters. This seems like an application of Reap
and Sow
. But the on-line documentation of these functions is pretty poor, and the examples don't add much. Shifrin's book keeps referring to a discussion of Reap and Sow in Part II, but I can't actually find a part II. Is there a resource somewhere that I can look at to understand the ins and outs of these functions, and see some real examples of how to use them?
The simple Reap[Map[Sow[#, #[[2]]] &, r]]
, where r
is the list above, produces almost what I want, but instead of {{a,c},x}
above, it produces {{a,x},{c,x}}
.
(I'm sure that someone will post a solution to my programming problem; for that I would be grateful. But I really would like to understand these functions better.)
EDIT: The code Reap[Map[Sow[#[[1]], #[[2]]] &, r], _, {#2, #1} &] // Rest
does the trick. Perhaps there's a better way. In any case, my question about documentation still stands.
GatherBy
is the way to go here. What in the docs is unclear/missing in your opinion? There are several answers usingReap
/Sow
around, a search may be useful. $\endgroup$Sow
was doing, but looking at more examples, I realized that providing an undefined function name as the third argument ofReap
will show me exactly what mySow
produced. I'm much happier now. AndGatherBy
with a little postprocessing worked as well, so now I have two possible solutions. $\endgroup$