我是R的新人,也是igraph。我想在两个节点集之间创建一个二分图(一个有2115个节点,另一个有4个节点),带有指定的边列表。这听起来很容易但我构建它有很多困难,到目前为止还没有结果。我将不胜感激任何帮助。这是我的代码:
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)
我不知道我的代码在哪里出错了,我想这都是因为我是新手。非常感谢您的帮助。
答案 0 :(得分:4)
以下是如何构建二分图的示例:
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])