Function Repository Resource:

PositionedCases

Source Notebook

Find positions and values within an expression matching a pattern

Contributed by: Bob Sandheinrich

ResourceFunction["PositionedCases"][expr,pattern]

gives an Association mapping positions of objects in expr matching pattern to their values.

ResourceFunction["PositionedCases"][expr,pattern,levelspec]

finds only positions and values that appear on the levels specified by levelspec.

ResourceFunction["PositionedCases"][expr,pattern,levelspec,n]

gives the positions and values of the first n objects found.

ResourceFunction["PositionedCases"][pattern]

represents an operator form.

Details and Options

ResourceFunction["PositionedCases"] accepts the same options as Position.
Like Position, the default level specification for ResourceFunction["PositionedCases"] is {0,Infinity} with HeadsTrue.

Examples

Basic Examples (3) 

Get positions of integers in an expression along with the integer values:

In[1]:=
ResourceFunction[
 "PositionedCases"][{{"a", 1, "b", 200}, {500, {6, "c"}}}, _Integer]
Out[1]=

Find values in an Association:

In[2]:=
ResourceFunction[
 "PositionedCases"][<|
  "schedule" -> <|
    "dates" -> <|"today" -> Today, "yesterday" -> Yesterday|>|>|>, _DateObject]
Out[2]=

Create an operator:

In[3]:=
op = ResourceFunction["PositionedCases"][_?OddQ]
Out[3]=

Use it:

In[4]:=
op[Range[10]]
Out[4]=

Scope (3) 

Use a pattern test and a level spec:

In[5]:=
ResourceFunction[
 "PositionedCases"][{{1, 2, 3, 4}, {5, 6, 7, 8}}, _?OddQ, {2}]
Out[5]=

Also limit the number of results:

In[6]:=
ResourceFunction[
 "PositionedCases"][{{1, 2, 3, 4}, {5, 6, 7, 8}}, _?OddQ, {2}, 2]
Out[6]=

Up to the first two levels:

In[7]:=
ResourceFunction[
 "PositionedCases"][{-1, 0, {1, 2, 3, 4}, {5, 6, 7, {8, 9, 10}}}, _?
  OddQ, 2]
Out[7]=

Options (1) 

Use the Heads option to control whether to include heads of expressions:

In[8]:=
ResourceFunction["PositionedCases"][f[g[h[1, 2, 3]]], g]
Out[8]=
In[9]:=
ResourceFunction["PositionedCases"][f[g[h[1, 2, 3]]], g, Heads -> False]
Out[9]=

Applications (2) 

Retrieve a dataset:

In[10]:=
data = ResourceFunction["KeyIndex"][
  ResourceData["Sample Data: Animal Weights"], "Species"]
Out[10]=

Find positions and values in given range:

In[11]:=
ResourceFunction[
 "PositionedCases"][data, _?(Quiet[
     Quantity[1, "Grams"] < # < Quantity[5, "Grams"]] &)]
Out[11]=

Version History

  • 1.0.0 – 27 February 2020

Related Resources

License Information