Wolfram Research

Function Repository Resource:

SelectAtLevel

Source Notebook

Select elements that satisfy a criterion at a certain level

Contributed by: Sander Huisman

ResourceFunction["SelectAtLevel"][list,crit,level]

picks out all elements ei of list at level level for which crit[ei] is True.

ResourceFunction["SelectAtLevel"][crit,level]

represents an operator form of ResourceFunction["SelectAtLevel"] that can be applied to an expression.

Details and Options

ResourceFunction["SelectAtLevel"] is analogous to Select except that Select only picks elements at level 1, while ResourceFunction["SelectAtLevel"] can also pick at deeper levels.

Examples

Basic Examples

Select prime numbers from a list of lists:

In[1]:=
ResourceFunction[
 "SelectAtLevel"][{Range[20], Range[10], Range[6]}, PrimeQ, 2]
Out[1]=

Scope

Select odd numbers in a deeply nested and ragged expression:

In[2]:=
ResourceFunction[
 "SelectAtLevel"][{{Range[5], Range[3]}, {Range[4], {"a", "b"}, {2, 3, 7, 1, 4}}}, OddQ, 3]
Out[2]=

Create an operator for SelectAtLevel:

In[3]:=
op = ResourceFunction["SelectAtLevel"][OddQ, 2]
Out[3]=

Use the operator:

In[4]:=
op[{Range[5], Range[-6, 8]}]
Out[4]=

The head does not need to be List:

In[5]:=
ResourceFunction["SelectAtLevel"][
 b[f["S", "a", "n", 2, "d"], g["a", 1, 2, 3, "b"]], IntegerQ, 2]
Out[5]=

Properties and Relations

SelectAtLevel is related to Select:

In[6]:=
ResourceFunction["SelectAtLevel"][Range[20], PrimeQ, 1] === Select[Range[20], PrimeQ]
Out[6]=

Possible Issues

All parts of list should at least be level deep:

In[7]:=
ResourceFunction[
 "SelectAtLevel"][{{"S", "a", "n", "d"}, {"a", 1, 2, 3, "b"}, "a"}, StringQ, 2]
Out[7]=

Resource History

Related Resources

License Information