# Swapping elements of list

Say I have a directed graph inputted in the following format in Mathematica:

g = {{1, "a", 2}, {2, "b", 1}}


I'd like to plot this graph using GraphPlot in Mathematica, which is the following syntax:

GraphPlot[{{1 -> 2, "a"}, {2 -> 1, "b"}}, VertexLabeling -> True, DirectedEdges -> True,
VertexCoordinateRules -> Auto, VertexLabeling -> True]


How would I swap the middle elements and the last elements in any list like g, so that g would look closer to the argument of GraphPlot?

{{1 -> 2, "a"}, {2 -> 1, "b"}}


I have searched the Mathematica documentation but was unable to find a good way of doing this.

• All you need is a simple replacement rule: g /. {f_Integer, m_String, l_Integer} :> {f -> l, m}
– rm -rf
Oct 28, 2013 at 3:48
• Thanks! That was really simple and clean. Oct 28, 2013 at 5:00
• Also g[[All, 1]] = Rule @@@ g[[All, {1, 3}]];g[[All, {1, 2}]] Oct 28, 2013 at 5:26

rm -rf has suggested the simplest solution which matches the elements and swaps them around:

g = {{1, "a", 2}, {2, "b", 1}};
g /. {a_Integer, b_String, c_Integer} :> {a -> c, b}
{{1 -> 2, "a"}, {2 -> 1, "b"}}


Graph[Labeled[#1 \[DirectedEdge] #3, Style[#2, 20]] & @@@ g] or with more formatting:

Graph[Labeled[#1 \[DirectedEdge] #3, Style[#2, 20]] & @@@ g,
VertexLabels -> Placed["Name", Center], VertexSize -> 0.2,
VertexLabelStyle -> 20] • Thanks for this-- yes, this also works, but alas I can only accept one answer. Oct 28, 2013 at 5:00