tolou
tolou

Reputation: 53

creating a bipartite graph in R with igraph with specific edge list

I am new in R and also igraph. I want to make a bipartite graph between two nodes sets (one has 2115 nodes and another one has 4) with specified edge list. It sound easy but I have lots of difficulties for constructing it and so far no result. I would appreciate any help. Here is my piece of codes:

library(igraph)
test <- graph.data.frame(file.choose(), directed=T)
edge <- read.table(text="e1 e2
779 958
779 1293
779 1503
1124 97
1124 151
2078 979
1970 344", header=T)
edgels <- graph.edgelist(as.matrix(edge))
g <- graph.bipartite(test, edgels, directed=T)

I don't know where my code is wrong and I guess it is all because I am new in this. Thanks so much for your helps.

Upvotes: 1

Views: 7193

Answers (1)

digEmAll
digEmAll

Reputation: 57210

Here's an exampe of how you can build a bipartite graph :

library(igraph)

#### create example input data
nodesSet1 <- 1:3
nodesSet2 <- 1:5
edgeList <- data.frame(S1=c(1,1,2,3,3,3),
                       S2=c(1,3,5,3,4,2))
####

### PREMISE :
### graph.bipartite function simply create a graph and add a boolean 'type' attribute
### to each vertex that indicate the partition of the vertex (e.g. TRUE first partition, 
### FALSE second partition).
### So, it's not strictly necessary to use that function to get a bipartite graph, but 
### you can use any method you like (or feel easier) as long as you add a 'type' 
### attribute. 
### Hence, in the following code I won't use graph.bipartite since I don't like it :)


# first we give prefixes to the nodes to discern the two partition
g <- graph.empty()
g <- add.vertices(g,nv=length(nodesSet1),attr=list(name=paste0('A',nodesSet1),
                                          type=rep(TRUE,length(nodesSet1))))
g <- add.vertices(g,nv=length(nodesSet2),attr=list(name=paste0('B',nodesSet2),
                                type=rep(FALSE,length(nodesSet2))))

# we need to turn edgeList into a vector (and using names instead of indexes)
edgeListVec <- as.vector(t(as.matrix(data.frame(S1=paste0('A',edgeList$S1),
                             S2=paste0('B',edgeList$S2)))))
g <- add.edges(g,edgeListVec)

# check if is recognized as bipartite
is.bipartite(g)

# let's plot it !
plot.igraph(g, layout=layout.bipartite,
               vertex.color=c("orange","green")[V(g)$type+1])

enter image description here

Upvotes: 6

Related Questions