# Using FindGraphCommunities, write community membership for each vertex to CSV

I have a network that I've loaded into Mathematica, and I've used FindGraphCommunitites[network,Method->"Hierarchical"] to identify the communities in the network.

I know that I can use CommunityGraphPlot[network] to visually plot the graph, however, I would like to export to CSV a list of each vertex in the graph and the community they belong to.

## Import .gml data
network=Import["file.gml"]

## Run community detection
FindGraphCommunitites[network,Method->"Hierarchial"]

## Number of communities
Length[FindGraphCommunitites[network,Method->"Hierarchial"]]

## Number of vertices in each community
Length/@FindGraphCommunitites[network,Method->"Hierarchial"]

## Plot network with community structure
CommunityGraphPlot[network,Method->"Hierarchial"]


rg = RandomGraph[WattsStrogatzGraphDistribution[30, 0.3, 3]]


gc = FindGraphCommunities[rg, Method -> "Hierarchical"]
(* {{6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17},
{4, 18, 19, 20, 21, 22, 23, 24, 25, 26},
{1, 2, 3, 5, 27, 28, 29, 30}} *)

CommunityGraphPlot[rg, gc]


expdata = Join @@ MapIndexed[Thread[{#1, First@#2}] &, gc]
(* {{6, 1}, {7, 1}, {8, 1}, {9, 1}, {10, 1}, {11, 1}, {12, 1},
{13, 1}, {14, 1}, {15, 1}, {16, 1}, {17, 1},
{4, 2}, {18, 2}, {19, 2}, {20, 2}, {21, 2}, {22, 2}, {23, 2},
{24, 2}, {25, 2}, {26, 2},
{1, 3}, {2, 3}, {3, 3}, {5, 3}, {27, 3}, {28, 3}, {29, 3}, {30, 3}} *)

Export["gcoms1.csv", expdata]


IGraph/M contains utility functions for converting back and forth between a representation of communities as sets or a membership vector: IGPartitionsToMembership, IGMembershipToPartitions.

partitions = FindGraphCommunities[network, Method -> "Hierarchical"]

table = Transpose@{VertexList[network], IGPartitionsToMembership[VertexList[network], partitions]}

Export["table.csv", table]


Of course, these are not difficult to implement from scratch, but I find that they are quite useful when dealing with various partitionings of graph vertices.