Generating an edge list from ID and grouping vectors

萝らか妹 提交于 2019-12-01 09:20:29

Instead of using split and lapply, you can use the dplyr package.

df <- data.frame(project.id = c('SP001', 'SP001', 'SP001', 'SP017', 'SP018', 'SP017'),
                 supplier.id = c('1224', '5542', '7741', '1224', '2020', '9122'),
                 stringsAsFactors = FALSE)

library(dplyr)

df %>% group_by(project.id) %>%
  filter(n()>=2) %>% group_by(project.id) %>%
 do(data.frame(t(combn(.$supplier.id, 2)), stringsAsFactors=FALSE))
# Source: local data frame [4 x 3]
# Groups: project.id [2]

#   project.id    X1    X2
#        (chr) (chr) (chr)
# 1      SP001  1224  5542
# 2      SP001  1224  7741
# 3      SP001  5542  7741
# 4      SP017  1224  9122

You can just merge it with itself which gets you all the Cartesian pairs:

 temp <- merge(df,df, by="project.id")
 res <- temp[ temp$supplier.id.x != temp$supplier.id.y , ]

> res

   project.id supplier.id.x supplier.id.y
2       SP001          1224          5542
3       SP001          1224          7741
4       SP001          5542          1224
6       SP001          5542          7741
7       SP001          7741          1224
8       SP001          7741          5542
11      SP017          1224          9122
12      SP017          9122          1224

We can try with igraph

library(igraph)
m1 <- get.edgelist(graph.adjacency(crossprod(table(df))))
m1[m1[,1]!= m1[,2],]
#      [,1]   [,2]  
#[1,] "1224" "5542"
#[2,] "1224" "7741"
#[3,] "1224" "9122"
#[4,] "5542" "1224"
#[5,] "5542" "7741"
#[6,] "7741" "1224"
#[7,] "7741" "5542"
#[8,] "9122" "1224"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!