如何从数据生成R中​​的igraph兼容边集

时间:2019-04-18 21:29:07

标签: r igraph edges

我有一个数据集,当前包含一组单词以及它们原来所在的段落,如下所示:

word <- c("wind", "statement", "card", "growth", "egg", "caption", "statement", "robin", "growth")
paragraph <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
data <- data.frame(word, paragraph)

并且我正在尝试为其生成一个igraph的边列表,该边列表基于每个词在同一个段落中的共现关系将其连接起来,

node1 <- c("wind", "wind", "statement", "statement", "card", "card", "growth", "growth", "egg", "egg", "caption", "caption", "statement", "statement", "robin", "robin", "growth", "growth")
node2 <- c("statement", "card", "wind", "card", "wind", "statement", "egg", "caption", "growth", "caption", "growth", "egg", "robin", "growth", "statement", "growth", "statement", "robin")
edges <- data.frame(node1, node2)

到目前为止,我只想出了如何使用

根据段落计算每个单词之间的相关性。
data <- data %>% group_by(word) %>% pairwise_cor(word, paragraph, sort = TRUE)

来自widyr软件包,但是对于其他要运行的操作,我确实需要边缘为共现的实际数量而不是相关系数。有谁知道是否有一些代码可以帮我解决这个问题?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

当我说“我确实需要边缘是共现的实际数量而不是相关系数”时,我不太确定您的意思。但是,“我正试图根据它在段落中的共现关系从每个词生成一个igraph的边列表,以连接每个词”。我的解释是,如果两个单词在同一段落中,则它们会链接在一起。您可以使用combn来创建这种边缘列表:

Edges = c()
for(p in unique(data$paragraph)) { 
    Edges = c(Edges, word[combn(which(data$paragraph == p), 2)]) }
EL = matrix(Edges, ncol=2, byrow=T)

library(igraph)

g = graph_from_edgelist(EL, directed=FALSE)
plot(g)

Graph from paragraphs