How to List the Set of In-links to a Node
Simple pattern matching:
Cases[edges, edge : (v_ -> 5) :> v]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
If you had specified the graph using DirectedEdge
instead, then the pattern would have looked like this:
Cases[DirectedEdge @@@ edges, edge : DirectedEdge[v_, 5] :> v]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
If you have a big graph, IncidenceList
can be used to efficiently narrow it down to all edges that are incident to a given node:
Cases[
IncidenceList[Graph[edges], 5],
DirectedEdge[v_, 5] :> v
]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
This leverages the graph functions even more:
g = Graph[edges];
m = IncidenceMatrix[g];
First /@ Extract[
EdgeList[g],
Position[m[[VertexIndex[g, 5], ;;]] // Normal, 1]
]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
A few additional alternatives:
VertexInComponent
Rest @ VertexInComponent[edges, 5,1]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
GroupBy
GroupBy[edges, Last -> First] @ 5
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
ReplaceAll
Rest @ DeleteDuplicates[5 /. List /@ Reverse /@ edges]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
SparseArray
+ "AdjacencyLists"
SparseArray[Reverse /@ List @@@ edges -> 1]["AdjacencyLists"][[5]]
{27, 23, 22, 21, 4, 25, 7, 24, 30, 15, 18, 19, 29, 3, 8, 9, 10}
Transpose[SparseArray[List @@@ edges -> 1]]["AdjacencyLists"][[5]]
{3, 4, 7, 8, 9, 10, 15, 18, 19, 21, 22, 23, 24, 25, 27, 29, 30}