I am creating a networkD3 forceNetwork(), but after I cleared my env vars in RStudio the network would not display in my browser when I ran the code a second time. Any idea why? No code errors. Var output is below.
library(networkD3)
library(igraph)
setwd("C:\\Users\\King\\Desktop\\SNA_Rcode")
csv<-read.csv("C:\\Users\\King\\Desktop\\Analysis\\mc_with_0_and_MI.csv")
df<-data.frame(csv$stat.deaths,csv[,4],csv$stat.mob)#damage delt on deaths, mob kills (is color)
#2 mode. interactive model
#g1 <- simpleNetwork(df) ; htmltools::html_print(g1, viewer = utils::browseURL)#DISPLAYS CORRECTLY
df <- df[!duplicated(df[,2]),]
df[,2] <- paste("", df[,2], sep="")
#setup
g <- graph.data.frame(df,directed=F)
links<-as.data.frame(get.edgelist(g)) #set name to number so calculate link correctly
links$V1<-as.numeric(as.character(links$V1))
links$V2<-as.numeric(as.character(links$V2))
colnames(links)<-c("source","target")
link_list<-(links-1)
#######################DOESNT WORK LIKE EXPECTED......replaces NA with 2 instead of 999
color_groups<-df[,3]# color based on mob kills
color_groups <- ifelse(as.numeric(color_groups) < 10, 1,
ifelse(as.numeric(color_groups) >= 30, 3, 2))
color_groups[is.na(color_groups)]<-999 #replace NA with 999
names<-0:(length(color_groups)-1)
node_list <- data.frame(name=names, group=color_groups)
profanity<-forceNetwork(Links = link_list, Nodes = node_list,Source = "source", Target = "target", NodeID = "name",Group = "group", opacity = 0.8, colourScale = "d3.scale.category10()",charge=-100)
htmltools::html_print(profanity, viewer = utils::browseURL)
After running all the above code (with a clear env):
> head(link_list,20)
source target
1 6 1169
2 1 839
3 1 2594
4 7 5409
5 11 2719
6 5 1719
7 7 179
8 2 1989
9 4 3444
10 0 2249
11 1 1964
12 0 3344
13 6 4479
14 6 2224
15 7 3869
16 5 2459
17 3 1704
18 -1 2479
19 5 3494
20 4 1869
> head(node_list,20)
name group
1 0 2
2 1 1
3 2 2
4 3 3
5 4 1
6 5 2
7 6 1
8 7 2
9 8 2
10 9 2
11 10 1
12 11 2
13 12 2
14 13 2
15 14 2
16 15 2
17 16 2
18 17 2
19 18 2
20 19 2
I needed to set the names for the vertices using:
V(g)$name<-1:104
after I initialized the graph (g)
Your link_list$source
and link_list$target
vectors appear to include indexes that are not in your node_list
, e.g. -1
and 2249
... or the values in those vectors are not what they are supposed to be...
The source
and target
vectors in the Links
data frame must be numeric, and their values refer to the index of the node in the Nodes
data frame which they represent (zero-indexed, unlike R, because it's used by the JavaScript code).
来源:https://stackoverflow.com/questions/30362911/forcenetwork-not-displaying-no-code-errors-returned