I am attempting to translate the following Python code (for Networkx
) into R (for 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
The following is my attempt at a partial conversion of from Python to 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")
}
This is the error code that I receive when I run the last portion of R code:
Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) :
no 'dimnames[[.]]': cannot use character indexing
In Python Networkx
, the graph can be called out by graphname.function (ex. DG.add_node(dogID,typ='animal')
).
Is there an equivalent in R's igraph
?
Is there any way to call out the nodes in R's igraph
without having to define the number of nodes?
Also, will you offer hints or suggestions on completing the translation to R?
Thank you.
The following contains the .csv data:
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,Influenza-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