Function Repository Resource:

AssociationTranspose

Source Notebook

Transpose the levels of an Association with nested levels

Contributed by: Ting Sun

ResourceFunction["AssociationTranspose"][assoc]

transposes the first two levels in assoc.

ResourceFunction["AssociationTranspose"][assoc,{n1,n2,}]

transposes assoc so that the kth level in assoc is the nkth level in the result.

ResourceFunction["AssociationTranspose"][assoc,m<->n]

transposes levels m and n in assoc, leaving all other levels unchanged.

Details and Options

ResourceFunction["AssociationTranspose"] mimics the way Transpose rearranges an array to reorganize the levels in an Association.
ResourceFunction["AssociationTranspose"][assoc] is equivalent to ResourceFunction["AssociationTranspose"][assoc,{2,1}].
For an Association of depth r3, ResourceFunction["AssociationTranspose"][assoc] is equivalent to ResourceFunction["AssociationTranspose"][assoc,{2,1,3,,r}].
The ni in ResourceFunction["AssociationTranspose"][a,{n1,n2,}] or ResourceFunction["AssociationTranspose"][a,n1<->n2] must be positive integers no larger than ArrayDepth[a].
{n1,n2,} has to be a complete permutation list.

Examples

Basic Examples (1) 

Transpose a simple nested Association:

In[1]:=
ResourceFunction[
 "AssociationTranspose"][<|1 -> <|a -> x|>, 2 -> <|a -> y|>|>]
Out[1]=

Scope (3) 

Create a nested Association with three levels:

In[2]:=
asc = ResourceFunction["AssociationKeyDeflatten"]@
   AssociationThread[
    Tuples[{Range[3], CharacterRange["a", "d"], CharacterRange["\[Alpha]", "\[Beta]"]}], RandomReal[1, 24]];
Dataset[asc]
Out[2]=

Transpose an Association of three levels using different permutations:

In[3]:=
asc = ResourceFunction["AssociationKeyDeflatten"]@
   AssociationThread[
    Tuples[{Range[3], CharacterRange["a", "d"], CharacterRange["\[Alpha]", "\[Beta]"]}], RandomReal[1, 24]];
In[4]:=
Dataset@ResourceFunction["AssociationTranspose"][asc]
Out[4]=
In[5]:=
Dataset@ResourceFunction["AssociationTranspose"][asc, {2, 3, 1}]
Out[5]=
In[6]:=
Dataset@ResourceFunction["AssociationTranspose"][asc, {1, 3, 2}]
Out[6]=
In[7]:=
Dataset@ResourceFunction["AssociationTranspose"][asc, {2, 3, 1}]
Out[7]=

Exchange levels 1 and 3 of an Association of three levels using TwoWayRule to express a permutation:

In[8]:=
asc = ResourceFunction["AssociationKeyDeflatten"]@
   AssociationThread[
    Tuples[{Range[3], CharacterRange["a", "d"], CharacterRange["\[Alpha]", "\[Beta]"]}], RandomReal[1, 24]];
In[9]:=
Dataset@ResourceFunction["AssociationTranspose"][asc, 3 <-> 1]
Out[9]=

Possible Issues (1) 

An invalid permutation specification causes an error:

In[10]:=
asc = ResourceFunction["AssociationKeyDeflatten"]@
   AssociationThread[
    Tuples[{Range[3], CharacterRange["a", "d"], CharacterRange["\[Alpha]", "\[Beta]"]}], RandomReal[1, 24]];
ResourceFunction["AssociationTranspose"][asc, {4, 2, 3, 1}]
Out[10]=

Publisher

Ting Sun

Version History

  • 1.0.0 – 12 December 2020

Related Resources

License Information