我有一个图表,其中节点属于两个不同的宗教,我需要选择一个宗教的节点并完全连接它们。是否有比以下更简洁的方式:
g<-graph.empty(n=0, directed=T)
## add nodes
g<-add.vertices(g, length(df[,1]), attr=df)
for(i in V(g)[religion == "x"]){
for(ii in V(g)[religion == "x"]){
if(i!=ii){
g<-add.edges(g, c(i,ii))
}
}
}
示例数据框可以是:
df<-structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), name = c("a", "b",
"c", "d", "e", "f", "g", "h", "i", "l", "m", "n"), village = c("A", "B", "C", "D", "E",
"F", "G", "H", "I", "L", "M", "N"), religion = c("x", "y", "y", "y", "y", "x", "x", "x",
"x", "x", "y","x"), adoption.lag = c(30, 32, 32, 32, 0, 30, 30, 30, 0, 1, 22, 22),
type = c("potter", "potter", "potter", "potter", "city", "potter", "potter", "potter",
"potter", "potter", "city", "potter")), .Names = c("id", "name", "village", "religion",
"adoption.lag", "type"), row.names = c(NA, -12L), class = "data.frame")
答案 0 :(得分:2)
这是一种简单的方法,而不是嵌套的for循环:
relnodes <- V(g)[religion == "x"]
g[relnodes, relnodes] <- 1
这是有效的,因为您可以将igraph图视为邻接矩阵。在这里查看更多示例: http://igraph.org/r/doc/graph.structure.html
如果要删除循环边缘,可以执行以下操作:
g <- simplify(g, remove.loops=TRUE, remove.multiple=FALSE)
答案 1 :(得分:1)
嗯,这是一种方式。
library(igraph)
x <- df[df$religion=="x",] # subset the df
z <- expand.grid(x$name,x$name) # every combination of edge
z <- with(z,z[Var1!=Var2,]) # remove loops
g <- graph.data.frame(z)
g <- add.vertices(g,nv=nrow(df)-nrow(x),attr=df[df$religion!="x",])
par(mar=c(0,0,0,0)) # set plot margins to 0...
plot(g)