我試圖將下面的Python代碼(Networkx
)轉換爲R(對於igraph
)。Python的Networkx到R igraph轉換有錯誤
# Python code
import csv
import networkx as nx
import urllib
DG=nx.DiGraph()
dogcsv=csv.DictReader(open("dogs.csv","rU"))
dogid=0
nodeStr=['id', 'species', 'Location 1', 'Location 2']
nodeInt=['sumflu']
fluCols=['Influenza-1', 'Influenza-2', 'Influenza-3', 'Influenza-4',
'Influenza-5', 'Influenza-6', 'Influenza-7', 'Influenza-8', 'Influenza-9']
for flu in fluCols:
DG.add_node(flu,typ="species")
for row in dogcsv:
dogID='animal'+str(dogid)
DG.add_node(dogID,typ='animal')
for dog in nodeStr:
DG.node[dogID][dog]=row[dog]
for dog in nodeInt:
DG.node[dogID][dog]=int(row[dog])
for flu in fluCols:
if str(row[flu])=='1':
DG.add_edge(dogID,flu)
dogid=dogid+1
以下是我在部分轉化嘗試從Python來R.
# R code
library("data.table")
library("igraph")
dogs <- make_empty_graph()
dogcsv <- fread("dogs.csv")
dogid <- 0
nodeStr <- c("id", "species", "Location 1", "Location 2")
nodeInt <- "sumflu"
fluCols <- c("Influenza-1", "Influenza-2", "Influenza-3", "Influenza-4",
"Influenza-5", "Influenza-6", "Influenza-7", "Influenza-8")
for(flu in fluCols) {
dogs[flu] <- dogs %>% add_vertices(8) %>% add_vertices(dogs[flu], typ = "host")
}
這是當我跑的R代碼裏面的最後部分,我收到錯誤代碼:
Error in intI(i, n = [email protected][1], dn[[1]], give.dn = FALSE) :
no 'dimnames[[.]]': cannot use character indexing
在Python Networkx
,曲線可以通過graphname.function(前調出。DG.add_node(dogID,typ='animal')
)。
在R的igraph
中是否有等價物?
有什麼辦法可以調出R的igraph
中的節點而不必定義節點的數量?
另外,您會提供完成R翻譯的提示或建議嗎?
謝謝。
下列包含該.csv數據:
ID,種類,位置1,位置2,動物ID,sumvirus,流感-1,流感-2,流感-3,流感-4,流感-5,流感-6,流感-7,流感-8,流感-9
YUI-4322,宿主1,公園4,公園,MW 391,1,0,0,0,0,0,0,0 ,0,0
YUI-4321,host2,Park 4,Park,MW 390,0,0,0,0,0,0,0,0,0,0
YUI-4320,host2,Park 4, Park,MW 389,1,0,0,0,0,0,0,0,0,0,0
YUI-4319,host2,Park 4,Park,MW 388,0,0,0,0,0, 0,0,0,0,0
YUI-7318,host2,Park 4,Park,MW 387,1,0,0,0,0,0,0,0,0,0,0
YUI-4317,host1,Park 4,Park,MW 386 ,0,0,0,0,0,0,0,0,0,0
YUI-4316,host2,Park 4,Park,MW 385,1,1,0,0,0,0,0, 0,0,0
YUI-2315,host1,Shelter 2,Shelter,MV319,1,0,0,0,0,0,0,0,0,0,1,0,0
YUI-4314,host1,Shelter 2, MV 332,1,0,0,0,0,0,0,1,0,0
您可能對[http://stackoverflow.com/questions/17433402/r-igraph-rename-vertices](this)感興趣。有一個igraph Python版本;也許作爲一箇中間步驟,你可以把它轉化爲這個。雖然你怎麼能離開networkx? ;-) –