igraph - 将节点矢量转换为R中所有可能边缘的数据帧

时间:2017-11-26 04:51:20

标签: r graph igraph

我正在研究R中的网络图,需要进行简单的数据操作。我有一个节点的数据框,看起来像这样:

dput(mynodes)
structure(list(id = c("s1", "s2", "s3", "s4", "s5", "s6", "s7", 
"s8"), name = c("Jim", "Mike", "Bob", "Joe", "John", "Rob", "Kyle", 
"Chad")), .Names = c("id", "name"), row.names = c(NA, 
-8L), class = "data.frame")

mynodes
  id name
1 s1  Jim
2 s2 Mike
3 s3  Bob
4 s4  Joe
5 s5 John
6 s6  Rob
7 s7 Kyle
8 s8 Chad

我想初始化这些节点之间所有可能边缘组合的数据帧。我想要的输出是一个如下所示的数据框:

   from   to
 1   s1   s2
 2   s1   s3 
 3   s1   s4 
 4   s1   s5 
 5   s1   s6
 6   s1   s7
 7   s1   s8 
 8   s2   s1
 9   s2   s3
10   s2   s4
... ... ... 

等等,来自mynodes的每个独特配对的所有方式。是否有一种简单的方法可以使用igraph包(因为我将使用igraph中的graph_from_data_frame函数创建网络)。

感谢任何帮助,谢谢!!

2 个答案:

答案 0 :(得分:1)

如果你想保存几行

df <- structure(list(id = c("s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"), name = c("Jim", "Mike", "Bob", "Joe", "John", "Rob", "Kyle", "Chad")), .Names = c("id", "name"), row.names = c(NA, -8L), class = "data.frame")


result <- as.data.frame(t(combn(df$id,2)))
colnames(result) <- c('from','to')

答案 1 :(得分:0)

我会在这里快速回答我自己的问题,因为我自己得到了它:

data.frame(from = rep(mynodes $id, each = length(mynodes $id)),
           to = rep(mynodes $id, times = length(mynodes $id)), 
           stringsAsFactors = FALSE) %>%
filter(to != from)