从 R 中的单列创建到节点 table

Create from to node table from single column in R

我想制作一个网络图来表示数据库中 table 之间的连接。我有一个包含以下列的数据框:

我不确定遍历数据帧以生成边缘 table 的最佳方法,该边缘 table 创建从 - 到列,其中“column_name” 相同(即 column_id 1 & 7).我的数据框有 1,500 多行。

如有任何帮助或指导,我们将不胜感激。

# Example dataframe with example values
df <- as.data.frame(rbind(
c("table_A", "column1", 1),
c("table_A", "column3", 2),
c("table_A", "column5", 3),
c("table_B", "column3", 4),
c("table_B", "column5", 5),
c("table_B", "column6", 6),
c("table_C", "column1", 7),
c("table_D", "column3", 8),
c("table_D", "column5", 9),
c("table_E", "column1", 10),
c("table_E", "column6", 11)
))

colnames(df)[1] <- "table_name"
colnames(df)[2] <- "column_name"
colnames(df)[3] <- "column_id"
# Example desired output using column_id
edges <- as.data.frame(rbind(
c(1,7),
c(1,10),
c(7,10),
c(2,4),
c(2,8),
c(4,8),
c(3,5),
c(3,9),
c(5,9),
c(6,11)
))

colnames(edges)[1] <- "from"
colnames(edges)[2] <- "to"

基本 R 选项

setNames(
  do.call(
    rbind,
    aggregate(
      column_id ~ column_name,
      df,
      function(x) list(data.frame(t(combn(x, 2))))
    )$column_id
  ), c("From", "To")
)

给予

   From To
1     1  7
2     1 10
3     7 10
4     2  4
5     2  8
6     4  8
7     3  5
8     3  9
9     5  9
10    6 11