1
$\begingroup$

My data has two columns that we'll call A and B. The columns proceed as such

A B

A1 B1

A2 B2

A3 B3

....

I'm trying to make this into a directed graph where A1 has an outgoing edge to B1 and similarly between A2 and B2 and so on

When I import the excel file, it creates a list like this

{{{person A1, person B1}, {person A2, person B2}, .... {person An, person Bn}}}

but I can't make a directed graph out of this. So how do I take this very simple two-column format and quickly make it into a directed graph going from persons in column A to persons in column B?

Any help would be appreciated

$\endgroup$
  • 3
    $\begingroup$ If your list is called lst, then perhaps Graph[Rule @@@ First@lst]. $\endgroup$ – march Feb 8 '16 at 18:20
  • 1
    $\begingroup$ You may also like to add VertexLabels -> "Name" as an option to Graph to get some simple labeling of your nodes. $\endgroup$ – MarcoB Feb 8 '16 at 18:23
  • $\begingroup$ The suggestions here did the trick! Thanks all $\endgroup$ – mo-money-mo-problems Feb 12 '16 at 3:26
  • $\begingroup$ But I'm still confused. what does "Rule @@@ First@lst" mean? I sort of get what each of those expressions means separately, but all together it's confusing $\endgroup$ – mo-money-mo-problems Feb 12 '16 at 3:58
2
$\begingroup$

If you need to do computation on the graph, and/or your graph is very large- working with a SparseArray and an AdjacencyGraph may prove the most beneficial.

Here is a random list which can resemble your data:

randomVals = Table[{RandomInteger[10], RandomInteger[20]}, 100];

Now we obtain a list of all the values in the list:

keys = Union[Join[values[[All, 1]], values[[All, 2]]]];

Index all the values in the list:

positions = Flatten[MapIndexed[{#1 -> First[#2]} &, keys]];

Create a sparse array object and fill it with values:

s = SparseArray[
     Flatten[{({#[[1]], #[[2]]} /. positions) -> 1} & /@ randomVals, 1],
     {Max[positions[[All, 2]]], Max[positions[[All, 2]]]}];

AdjacencyGraph[s]

adj graph

p.s. after doing computation on the graph you can always translate the node numbers back to your labels with the reverse of your position vector:

(*node values*) /. (Reverse /@ positions)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.