# Reap and Sow Tags. How to retrieve part of list belonging to specific tag? [closed]

I'm trying to improve my code's performance by using reap and sow instead of appendto and it works, but I hit a small obstacle. Since my code is building two lists simultaneously, I need to use sow with tag and afterwards I take the two resulting things from it. But I don't know which is which! I used tag to construct the lists so it seems natural to expect I would be able to call the parts of the output with that tag, like outputlist[[ tag used ]] or something similar. But I couldn't find anything like it.

The best solution I can think of is to just add a token element to each tag and I know that the list with a first element "this is from tag 1" is the tag 1 list. But if there's a more elegant way of doing that it would be nice.

• Example? -- or maybe Reap[<code>, {"tag1", "tag2"}]? Nov 21, 2018 at 0:47
• You can turn the second element in the output of Reap into an Association. Then you can access the tags as desired. Nov 21, 2018 at 0:53
• Look at the docs for Reap under "Scope", "Generalizations & Extensions" and "Properties & Relations" -- there's one relevant example in each section Nov 21, 2018 at 1:02

Now that Carl Woll constructed a minimal example, I can expand on my comment. You can turn the result of Reap into an association and access the tagged bins by using the tag as key:

harvest = Association@Reap[
Sow[1, "tag1"];
Sow[2, "tag1"];
Sow[3, "tag2"],
{"tag1", "tag2"},
Rule][[2]]


<|"tag1" -> {1, 2}, "tag2" -> {3}|>

Now you can access the binned data as follows:

harvest[["tag1"]]
harvest[["tag2"]]


{1, 2}

{3}

The Sow-and-Reap mechanisms is much older (version 5.0?) than Association (version 10.0). I bet that Reap would have been implemented to return an association if it would have been added to the language after Association. Now, it has to remain as it is for backward compatibility.

Caution: Be careful with integers as keys for an association: heavest[[1]], heavest[1], and heavest[[Key[1]]] behave quite differently when you use integer keys.

Maybe you can tweak the following to suit your purposes:

Reap[
Sow[1,"tag1"]; Sow[2,"tag1"]; Sow[3,"tag2"],
{"tag1", "tag2"},
Rule
]


{3, {{"tag1" -> {1, 2}}, {"tag2" -> {3}}}}