Function Repository Resource:

ApplyLevel

Source Notebook

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

Contributed by: Seth J. Chandler

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

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

Details and Options

ResourceFunction["ApplyLevel"][f,levelspec] returns an expression with head Curry.
ResourceFunction["ApplyLevel"][f,{0}] is the same as Apply[f].

Examples

Basic Examples (2) 

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

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

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

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

Scope (2) 

ApplyLevel works with Association, just as Apply does:

In[3]:=
density = #1/(4/3 \[Pi] #2^3) &;
In[4]:=
ResourceFunction["ApplyLevel"][
  density, {2}][<|"Moons" -> <|"Phobos" -> <|"Mass" -> Quantity[1.0724880884600402`3.9586073148417724*^16, "Kilograms"], "Radius" -> Quantity[11.1`3., "Kilometers"]|>, "Deimos" -> <|"Mass" -> Quantity[1.468340774924336`1.9995659225206786*^15, "Kilograms"], "Radius" -> Quantity[6.2`2., "Kilometers"]|>|>|>]
Out[4]=

ApplyLevel works on SparseArray objects just as it would on the corresponding ordinary lists:

In[5]:=
sparse = SparseArray[{{1, 1} -> 1, {2, 2} -> 2, {3, 3} -> 3, {1, 3} ->
     4}]
Out[5]=
In[6]:=
MatrixForm[sparse]
Out[6]=
In[7]:=
ResourceFunction["ApplyLevel"][f, {1}][sparse]
Out[7]=

Applications (2) 

Turn an Association in which the values are lists of vertex pairs into lists of undirected edges:

In[8]:=
groupedEdges = <|6487 -> {}, 16243 -> {}, 16245 -> {}, 16246 -> {}, 6572 -> {{6472, 6473}}, 6573 -> {{6472, 6473}}, 6571 -> {}, 6575 -> {{6474, 6475}, {6474, 6478}, {6475, 6478}}, 6576 -> {{6474, 6478}}, 6577 -> {{6474, 6475}, {6474, 6478}, {6475, 6478}}, 16241 -> {{6474, 6475}}, 16239 -> {}, 6574 -> {{6475, 6478}}, 16237 -> {}, 16784 -> {}, 16240 -> {}, 14667 -> {}, 19427 -> {}, 16238 -> {}, 16244 -> {}, 18709 -> {{6481, 6483}, {6481, 6484}, {6483, 6484}}, 15336 -> {{6482, 6485}, {6482, 6486}, {6485, 6486}}|>;
In[9]:=
ResourceFunction["ApplyLevel"][UndirectedEdge, {2}][%]
Out[9]=

Now convert the result into a multigraph:

In[10]:=
Graph[Flatten@Values[%]]
Out[10]=

Neat Examples (2) 

Compute the density of all the planetary moons, by first retrieving the planets Dataset:

In[11]:=
planets = ExampleData[{"Dataset", "Planets"}]
Out[11]=

Now use ApplyLevel as part of a pipeline of operators:

In[12]:=
(Map[Map[ResourceFunction["ApplyLevel"][density, {1}]]/*(#Moons &)]/*
   Select[Length[#1] > 0 &])[planets]
Out[12]=

Publisher

Seth J. Chandler

Version History

  • 1.0.0 – 27 January 2020

Related Resources

License Information