What's the difference between Part
and Position
?
How can I "move" from the form used by Part
to that of Position
(and vicerversa?)
Thanks!
The part specification used by Position
is shared by Extract
:
g = Plot[Sin[x], {x, 1, 5}];
pos = Position[g, _Directive]
Extract[g, pos]
{{1, 1, 3, 1}, {2, 11, 2}} {Directive[ (* omitted *) ], Directive[GrayLevel[0.5, 0.4]]}
Note that Extract
supports extracting multiple disjoint subexpressions at once. Part
can only extract one of these at a time.* Each part specification such as {1, 1, 3, 1}
needs to be converted from a list into a bare sequence. Available methods include pattern replacement and Function
/SlotSequence
along with Apply
at level one (short form @@@
):
Replace[pos, {x__} :> g[[x]], 1]
g[[##]] & @@@ pos
* These meaning the two elements in pos
in my example. Part
specifications at each level may be disjoint but apply to all parts in the extraction. Positions must have all but the last index in common.
m = Partition[Range@9, 3]
$\left( \begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{array} \right)$
m[[2, {1, 3}]]
{4, 6}
Index 2
applies to all elements extracted; one cannot extract (only) elements 4 and 9 with a single evaluation of Part
for example, whereas you can with Extract
:
Extract[m, {{2, 1}, {3, 3}}]
Part
&Position
$\endgroup$