问题
I wrote some R code that simulates some graph network based data, creates a graph, removes nodes if there are less than 2 connections and makes it an interactive graph. However, when I plot the graph, I can clearly see that nodes with 0 connections are still there (if nodes with less 2 connections are deleted, this means nodes with 1 connection and 0 connections should also be deleted).
Here is a picture that shows nodes with 0 connections have not been deleted:
Can someone please tell me what I am doing wrong?
set.seed(1234)
library(dplyr)
library(visNetwork)
library(igraph)
#create file from which to sample from
x5 <- sample(1:10000, 10000, replace=T)
#convert to data frame
x5 = as.data.frame(x5)
#create first file (take a random sample from the created file)
a = sample_n(x5, 9000)
#create second file (take a random sample from the created file)
b = sample_n(x5, 9000)
#combine
c = cbind(a,b)
#create dataframe
c = data.frame(c)
#rename column names
colnames(c) <- c("a","b")
#create graph
graph <- graph.data.frame(c, directed=F)
graph <- simplify(graph)
G=graph
#delete node if less than 1 connection
Isolated = which(degree(G)<2)
G2 = delete.vertices(G, Isolated)
#prepare for visnetwork
nodes <- data.frame(id = V(G2)$name, title = V(G2)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(G2, what="edges")[1:2]
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE) %>%
visInteraction(navigationButtons = TRUE)
Thanks
edit : function kindly provided by user20650
dirty <- function(g, n=2){
d = degree(g) < n
ds = sum(d)
print(ds)
if(ds == 0) {
return(g)
} else {
dirty(delete_vertices(g, which(d)))
} }
来源:https://stackoverflow.com/questions/64949960/r-deleted-nodes-are-still-showing-up-after-they-were-deleted