Wolfram Research

Function Repository Resource:

MapLevel

Source Notebook

Create an operator that maps a function over data at a specified level

Contributed by: Seth J. Chandler

ResourceFunction["MapLevel"][f,levelspec][data]

maps the function f over data at the level set forth in levelspec.

Details and Options

ResourceFunction["MapLevel"][f,levelspec] returns an expression with head Curry.

Examples

Basic Examples

Create a Map function that will apply a function f exclusively at parts of the expression lying at level 2:

In[1]:=
ResourceFunction["MapLevel"][f, {2}]
Out[1]=

Apply the function just created to an expression that is of depth 3:

In[2]:=
%[{{1, 2, 3}, {4, 5, {6, 7}}}]
Out[2]=

Scope

MapLevel works with integer level specifications in the same way as Map:

In[3]:=
ResourceFunction["MapLevel"][f, 2][{{1, 2, 3}, {4, 5, {6, 7}}}]
Out[3]=

MapLevel works with Association, just as Map does:

In[4]:=
ResourceFunction["MapLevel"][h, {2}][<|a -> <|b -> c|>, d -> <|e -> f|>|>]
Out[4]=

MapLevel works at multiple levels of an association:

In[5]:=
ResourceFunction["MapLevel"][h, {1, 3}][<|a -> <|b -> c|>, d -> {<|e -> f|>}|>]
Out[5]=

Applications

Of people over age 40 on the Titanic, find the survival numbers broken down by cabin class, using MapLevel as part of a pipeline of operators:

In[6]:=
(Select[#age > 40 &] /* GroupBy[Key["survived"]] /* ResourceFunction["MapLevel"][#class &, {2}] /* ResourceFunction["MapLevel"][Counts, {1}])[
 ExampleData[{"Dataset", "Titanic"}]]
Out[6]=

Properties and Relations

MapLevel produces what can be thought of as a nested Map operator:

In[7]:=
Map[Map[f]][{{1, 2, 3}, {4, 5, 6}}] === ResourceFunction["MapLevel"][f, {2}][{{1, 2, 3}, {4, 5, 6}}]
Out[7]=

MapLevel provides a vocabulary for understanding how Query works:

In[8]:=
Query[f, g, h][
  Array[x, {2, 3, 4}]] === (ResourceFunction["MapLevel"][h, {2}] /* ResourceFunction["MapLevel"][g, {1}] /* ResourceFunction["MapLevel"][f, {0}])[Array[x, {2, 3, 4}]]
Out[8]=

Resource History

License Information