r - 使用 R 简单转换为边缘列表?

标签 r igraph data-conversion edges

我需要在 R 中进行简单的数据转换以与 igraph 一起使用。我的数据框采用这种格式,按 GROUP 分组:

    A   GROUP
1   1       a
2   2       a
3   3       a
4   4       a
5   1       b
6   3       b
7   5       b

1. 如何扩展组以获得无向边列表el以这种格式?
    A   B
1   1   2
2   1   3
3   1   4
4   2   3
5   2   4
6   3   4
7   1   3
8   1   5
9   3   5

注意:没有自我引用 1-1, 2-2, 3-3, ...

2. 如何计算 A-B 出现次数并从 el 创建加权边列表?
    A   B   weight
1   1   2        1
2   1   3        2
3   1   4        1
4   2   3        1
5   2   4        1
6   3   4        1
7   1   5        1
8   3   5        1

最佳答案

这是一个解决方案,我在代码中注释:

# your data
df <- data.frame(A = c(1, 2, 3, 4, 1, 3, 5),
             GROUP = c("a", "a", "a", "a", "b", "b", "b"))

# define a function returning the edges for a single group
group.edges <- function(x) {
  edges.matrix <- t(combn(x, 2))
  colnames(edges.matrix) <- c("A", "B")
  edges.df <- as.data.frame(edges.matrix)
  return(edges.df)
}

# apply the function above to each group and bind altogether
all.edges <- do.call(rbind, lapply(unstack(df), group.edges))

# add weights
all.edges$weight <- 1
all.edges <- aggregate(weight ~ A + B, all.edges, sum)
all.edges
#   A B weight
# 1 1 2      1
# 2 1 3      2
# 3 2 3      1
# 4 1 4      1
# 5 2 4      1
# 6 3 4      1
# 7 1 5      1
# 8 3 5      1

关于r - 使用 R 简单转换为边缘列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850514/

相关文章:

R igraph 弯曲边缘

r - 改进 R 中网络图的布局和分辨率

python igraph : nodes and edges color according to a number associated to the node

c++ - 评估字符串的 bool 函数

python:以 block 的形式读取 csv 时,将 pandas 分类值转换为整数

r - 从一串函数名中选择一个函数,并通过管道连接到它

r - 在点阵图中的 y 轴上显示 "0"标签

r - 当表达式返回长度为零时,使R stopifnot或类似的简单函数引发错误

r - texmaker 上的 knitr 错误

python - 将数据从 .csv 文件转换为 .json - Python