r - 准备一个单列中包含多个节点的数据框以在 igraph 中使用

标签 r dplyr igraph

我有一个数据框,格式大致如下:

df1 <- data.frame(
    x = c(
        "Ben, Ellen", 
        "BV, Ellen, Trev", 
        "Ben, Trev, Pat", 
        "Ellen, Ben", 
        "Ev, Ryan"))

其中每个观察都是一组节点( friend )。

我想对数据进行igraph处理,但我假设它首先需要看起来像这样:

df2 <- data.frame(
    x = c(
        "Ben","BV","BV","Ellen","Ben",
        "Ben","Trev","Ellen","Ev"),
    y = c(
        "Ellen","Ellen","Trev","Trev","Trev",
        "Pat","Pat","Ben","Ryan"))

如何对每个观察进行字符串分割并确保每个节点( friend )与观察中的每个其他节点链接?基本上,如何将 df1 转换为 df2

最佳答案

使用基本函数可能更容易

ss <- strsplit(as.character(df1$x),", ")
el <- do.call("rbind", Map(function(x) t(combn(x,2)), ss))

返回的数据

      [,1]    [,2]   
 [1,] "Ben"   "Ellen"
 [2,] "BV"    "Ellen"
 [3,] "BV"    "Trev" 
 [4,] "Ellen" "Trev" 
 [5,] "Ben"   "Trev" 
 [6,] "Ben"   "Pat"  
 [7,] "Trev"  "Pat"  
 [8,] "Ellen" "Ben"  
 [9,] "Ev"    "Ryan" 

你可以用 igraph 绘制它

plot(graph_from_edgelist(el))

enter image description here

关于r - 准备一个单列中包含多个节点的数据框以在 igraph 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001566/

相关文章:

根据向量 C 或 D 的值从向量 A 或 B 返回元素

r - 尝试在 R 中使用朴素贝叶斯学习器,但 Predict() 给出的结果与模型建议的结果不同

r - 如何根据字符串变量对数值变量的值求和

R dplyr pivot wider with duplicates 并生成变量名

python - 我应该使用哪种布局在 python 中的 igraph 中获得非重叠边缘?

R - Igraph - 度函数似乎在 linux 环境中不起作用

r - 使用 ggparty 的决策 TreeMap 边缘的小数位数

r - 如何使用 lm、do、broom 和 dplyr 按组计算回归?

r - 如何知道图中的哪些节点是可移动的

r - ggplot2 geom_plot 值在同一栏中