Function Repository Resource:

GatherByIndex

Source Notebook

Combine items into sublists based on their position

Contributed by: Bob Sandheinrich

ResourceFunction["GatherByIndex"][list,f]

gathers into sublists each set of elements in list that gives the same value when f is applied to its index.

Details and Options

ResourceFunction["GatherByIndex"] works only at the first level of list.

Examples

Basic Examples (1) 

Gather consecutive characters using Mod:

In[1]:=
ResourceFunction["GatherByIndex"][CharacterRange["a", "m"], Mod[#, 3] &]
Out[1]=

Scope (1) 

See which words Shakespeare's Mark Antony used at prime locations:

In[2]:=
Last@ResourceFunction["GatherByIndex"][
  TextWords[ResourceData["Friends, Romans, Countrymen"]], PrimeQ]
Out[2]=

Applications (2) 

This is data showing activity of requests on a server for each hour over several months:

In[3]:=
data = CompressedData["
1:eJxNmnl8VdW1x/e+Nzf3AjKLUkRIEBACBBABIcgQ5jAEYwxjS6AUIoiAQqX6
BBRwqMWhQnGgiAris5WiVbAOdaitQwu2gtWqPNGqrTyqVWuftmrf+rJ+53P4
Y33OHc7Zew2/9Vtr731K5y6puTCGEI6cEEJXu063L49kQvi5fX7epMHkNZNf
mUwyaWtyksl8k1YmOZOFJiNMDpl0MjnZpN5koMlkkz0mJSZ9TNqZNCkO4cc2
z0qTh+z7iSYtTe43ucbkas0XJTxzvcnKfAhldn3Z5HSTniZTTMpNzjE51aSN
SQuTSumy3gaYaLI1+v1ZkyqTpSbn63Nvk0s1/wPSt4NJN+mNTjNlE/Pim4tN
l1l23W9yhskEk3fNLnNduMXkSZMeJkUmdmsomNRqnqMmg2TXVpO7TS4wGSaf
8vuZ0cd/UWNH6d7RpLF9GSV/V5iMlq2MWabrOJMZJgtMHjS50+Rck1LFkFh8
YfrewDM23lN2bW1yr+J8tmL6PeIbfY5vRfd1Z8k4+QmfnGUyzeQ/JjvtvvV2
nWOyhjjZ98127a64rNWzYOhvJgdNfmJyhWIyVnEBP0PAR8bjOlS++aPJvxVz
xvyDyS/la3z0rMk3TNqbHDH5szCCPQPkA4N76GIyVbYyF/gYH3yuVvqMnrsY
L3o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p1NjE/B09
O1g+S95L/FTPMMbU467wPn0dfRa8SQ9Oz/6m9Dz2fpV8sVDjDjzOHvzfVv4h
dnBag3SAZ29V3JjvypzXHPBIL/qq+Iq6+iudweBLuI+ekNpBXeE9o32KYU/p
Aobgo9uk/2JhA53PVTzAREN0n1+lmB0o9nqNjj2kPzGAp8H3Wj2b9JXEhLq+
SuNwhgdW6Acnqfev1HPUOfLwn/LlXsUW/qGXuDN4DUf3lfL/28L9OOkLLuEU
1j7UPjAN5sAVWMVf5AfvPXAeCD5by/etjKSHF3u8+md8zAvt+yv2fWvO8QAn
ztdY7Rp5PfvoOJ0rQ7pXgg/ojcD/7dH9Sl9crftqZDccQb8L/qid5NdUm++p
vGPmdcWFmgk3XhAdE3A9vEYekeeD5CPm3yaMYe924aeL5kA3+KRcz6BLd93T
VjgYaPYvK/LamOhYqZizD8L7GmCR9SY5x/kDvdOQkJ4Xcj32nmF0bkzeMzxT
uo8O6T4YZ8Ozbc6bottzQHE+9v62+IqxeR+AHqObYp30E51D+m4SOTZNPoWX
c4oXcYIP5goPnJ02qG+/WnrRd7NPBFfhYzhoSzPn0hrFgBynPq6X4DP6B9a8
yb5nck3O5dHj/wGxTtmU
"];
In[4]:=
ListPlot[data]
Out[4]=

Stack each hour to show daily trends:

In[5]:=
ListPlot[Total /@ ResourceFunction["GatherByIndex"][data, Mod[#, 24] &]]
Out[5]=

Properties and Relations (2) 

MapIndexed uses the full part specification given as a List:

In[6]:=
MapIndexed[(Print[#2]; #1) &, {"a", "b", "c"}]
Out[6]=

GatherByIndex is applied to the index at the first level, so the position is not given as a List:

In[7]:=
ResourceFunction["GatherByIndex"][{"a", "b", "c"}, Print]
Out[7]=

Version History

  • 1.0.0 – 30 June 2020

Related Resources

License Information