Python Networkx到R igraph转换有错误

时间:2017-05-16 03:13:54

标签: python r igraph networkx

我正在尝试将以下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 = x@Dim[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,species,Location 1,Location 2,animal id,sumvirus,Influenza-1,Influenza-2,Influenza-3,Influenza-4,Influenza-5,Influenza-6,Influenza-7,Influenza-8,流感9
YUI-4322,host1,Park 4,Park,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
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
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,1,0,0
YUI-4314,host1,Shelter 2,Shelter,MV 332,1,0,0,0,0,0,0,1,0,0

1 个答案:

答案 0 :(得分:0)

我对你正在做的事感到困惑,但我可以告诉你,狗是一个图形对象,而你正试图在一条线上做多件事,这些事情并不合理。

召唤狗[flu]给所有与流感相关的顶点。

add_vertices(8)正在向图表中添加8个新顶点。

add_vertices(dogs [flu],typ =&#34; host&#34;)正在将相同的节点添加到图中,如果狗[flu]可以调用则该节点已经存在。

只需添加之前的所有节点(add_vertices [fluCols],尽管它可能需要整数而不是字符串),然后在之后修改这些节点。