在R中通过共同的朋友连接节点 [英] Connecting nodes by common friends in R

查看:9
本文介绍了在R中通过共同的朋友连接节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个使用iggraph的转发网络工作。我的网络是定向的,这意味着它连接了从其他用户转发推文的人。

我的格式是边缘列表,其中箭头从转发者到被转发者,转发者之间没有连接(也就是说,所有转发者的内度数都是0,因为他们不会互相转发)。

我想通过普通朋友来连接转发者,简化网络。为此,我希望通过常见的转发用户来连接用户:

考虑以下重复:

edgelist <- read.table(text = "
                       A C
                       B C
                       D C")

g <- graph.data.frame(edgelist, directed = T)

在本例中,节点A、B和E从节点C转发推文,因此我希望通过以下方式连接所有这些节点:

理想情况下,我还可以根据用户转发推文的次数来加权,我希望将其合并到最终网络中,但这可能是另一个需要解决的问题。

我尝试了以下功能,它在小玩具网络中确实有效,但当我在我的(数千条边)中尝试它时,它崩溃了:

connect_friends<-function(edgelist){
  g <- graph.data.frame(edgelist, directed = T)
  g <- delete_vertices( g, 
                        (!V(g) %in% c(V(g)[[degree(g, mode = "in")>=2]])) & 
                          (!V(g) %in% c(V(g)[[degree(g, mode = "in")==0]])))
  el <- as.data.frame(get.edgelist(g))
  ids <- unique(c(el$V1, el$V2))
  
  y <- lapply(ids, function(id) {
    
    x <- el[which(el$V1 == id | el$V2 == id),]
    alt_nodes <- setdiff(unique(c(x$V1, x$V2)), id)
    
  })
  
  if(length(y)==0) {
    stop("No common friends found")
  }
  ne2=NULL
  ne=NULL
  for (i in 1:length(y)) {
    new_edge <- y[[i]]
    if (length(new_edge)>=2){
      ne <- t(combn(new_edge,2))
    }
    ne2 <- rbind(ne,ne2)
  }
  g2  <<-  graph.data.frame(ne2, directed  =  F)
  
}


有没有更有效的方法?

提前感谢!

推荐答案

更新

使用更新后的示例,我们可以获得

> gres
IGRAPH a824a46 UN-- 4 0 -- 
+ attr: name_1_1 (g/c), name_1_2 (g/c), name_2_1 (g/c), name_2_2 (g/c),
| loops_1_1 (g/l), loops_1_2 (g/l), loops_2_1 (g/l), loops_2_2 (g/l),
| name (v/c)
+ edges from a824a46 (vertex names):

plot(gres)显示

您可以使用disjoint_union+split+make_full_graph,如下

gres <- do.call(
  graph.union,
  lapply(
    names(V(g))[degree(g, mode = "out") == 0],
    function(x) {
      nbs <- names(V(g))[distances(g, v = x, mode = "in") == 1]
      disjoint_union(
        set_vertex_attr(make_full_graph(length(nbs)), name = "name", value = nbs),
        set_vertex_attr(make_full_graph(1), name = "name", value = x)
      )
    }
  )
)

这给了

> gres
IGRAPH cb11da8 UN-- 4 3 -- 
+ attr: name_1 (g/c), name_2 (g/c), loops_1 (g/l), loops_2 (g/l), name
| (v/c)
+ edges from cb11da8 (vertex names):
[1] A--B A--D B--D

plot(gres)显示

这篇关于在R中通过共同的朋友连接节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆