2014-02-28 113 views
0

我有一個圖表,其中節點屬於兩個不同的宗教,我需要選擇一個宗教的節點,並完全連接它們。有沒有一種更簡潔的方式比:如何完全連接節點選擇

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

請提供一些示例數據和附加的內容(包括什麼包/ s的你使用)。沒有它,目前還不清楚你在問什麼。 – Thomas

+0

你如何創建'g'?你的數據幀代碼被最後一個雙引號破壞,順便說一句。 –

+0

剛編輯我的問題 – user299791

回答

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) 
+0

確實很清楚,我會檢查鏈接 – user299791

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)