R: Deleted Nodes are Still Showing Up After They Were Deleted

拈花ヽ惹草 提交于 2020-12-13 16:20:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!