R: 将表格转换为邻接矩阵或边列表

2 投票
1 回答
931 浏览
提问于 2025-04-18 15:58

我有一个这样的表格:

1   "x1"    "x2"            
1   "x1"    "x2"    "x3"
1   "x1"    "x2"
2   "y1"    "y2"    "y3"
2   "y1"    "y2"    "y3"
3   "y1"    "x2"
3   "z1"    "x2"

我需要把这个表格转换成一个邻接矩阵或者边列表,这样我就可以把第一列当作边的属性,而其他列则是我的边。例如,我需要那些有超过3条边的行,它们都要像这样连接起来(以第2行为例):

"x1" "x2" 1
"x1" "x3" 1
"x2" "x3" 1

这里的“一个”表示我想要的边的类型。

有没有办法在R或者Python中做到这一点?

我打算用R中的igraph来绘制这个图。

1 个回答

2

我找不到一个简单的转换方法。不过,使用你的示例数据:

dd <- structure(list(V1 = c(1L, 1L, 1L, 2L, 2L, 3L, 3L), V2 = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L), .Label = c("x1", "y1", "z1"), class = "factor"), 
    V3 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L), .Label = c("x2", 
    "y2"), class = "factor"), V4 = structure(c(1L, 2L, 1L, 3L, 
    3L, 1L, 1L), .Label = c("", "x3", "y3"), class = "factor")), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -7L))

我最终创建了一些辅助函数,并使用了magrittr的语法,这种语法是dplyr喜欢用的,最后得到了这个结果:

library(magrittr)

smoosh <- function(...) do.call(Map, c(list(cbind.data.frame), list(...)))
collpase <- function(x) do.call(rbind, x)
has.char <- function(x) x[nchar(x)>0]

xx <- dd[-1] %>% as.matrix %>% split( 1:nrow(dd)) %>% lapply(has.char) %>% 
    lapply(combn,2) %>% lapply(t) %>% smoosh(attr=dd$V1) %>% collpase

正如你所看到的,有很多小的转换操作,这就是我选择使用%>%运算符来处理magrittr的原因,而不是把它们都嵌套在一起,这样更容易阅读。但最终它返回的是:

     1  2 attr
1   x1 x2    1
2.1 x1 x2    1
2.2 x1 x3    1
2.3 x2 x3    1
3   x1 x2    1
4.1 y1 y2    2
4.2 y1 y3    2
4.3 y2 y3    2
5.1 y1 y2    2
5.2 y1 y3    2
5.3 y2 y3    2
6   y1 x2    3
7   z1 x2    3

撰写回答