首页 > 解决方案 > 如何将模式转换为二分投影中的属性

问题描述

我有一个关于在转换为单模投影后保留节点信息的快速问题。

library(igraph)
data <- data.frame( company=c(letters[1:5],letters[5:8],"a"), Deal=c(14,14,15,15,16,16,17,17,18,18))
g <- graph_from_data_frame(data)
V(g)$type <-  V(g)$name %in% data[,1]
proj <- bipartite.projection(g)
proj$proj2

我想使用公司与公司之间的联系作为我的新边缘列表,但保留交易编号作为边缘属性,以便理想情况下我会有一个如下所示的新数据集:

来源 目标 交易
ab 14
cd 15
fg 17
ha 18

其中“来源”、“目标”和“交易”分别位于各自的列中。(对不起,这看起来不漂亮!)

我可以创建一个包含源和目标的数据框,但是我很难弄清楚如何在第三列中添加回交易。任何建议或指导将不胜感激!这是我正在使用的代码:

el00<-as_edgelist(proj$proj2)
colnames(el00) <- c("Source", "Target")     



   

标签: rigraphbipartitestatnet

解决方案


我会自己进行投影,并使用自己full_join()的 edgelist 进行投影,然后使用它igraph::simplify()来保留交易编号:

library(igraph)
#> 
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#> 
#>     decompose, spectrum
#> The following object is masked from 'package:base':
#> 
#>     union
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:igraph':
#> 
#>     as_data_frame, groups, union
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
data <- data.frame( 
  company=c(letters[1:5],letters[5:8],"a", "a", "b"), 
  Deal=c(14,14,15,15,16,16,17,17,18,18,19,19)
)

# Project onto company mode "by hand". This is a multigraph, i.e. there might be
# mulitple edges (with different deal numbers) between a pair of companies.
edb <- data %>%
  full_join(data, by = "Deal") %>%
  filter(company.x < company.y) %>%
  select(
    v1 = company.x,
    v2 = company.y,
    Deal
  )
edb
#>   v1 v2 Deal
#> 1  a  b   14
#> 2  c  d   15
#> 3  f  g   17
#> 4  a  h   18
#> 5  a  b   19

# Make the graph and simplify preserving the `Deal` as the unique deal numbers
g <- edb %>%
  graph_from_data_frame(directed=FALSE) %>%
  simplify(
    edge.attr.comb = unique
  )
# The edge attribute Deal is a list of deal numbers. E.g. companies 'a' and 'b'
# are engaged together in deals 14 and 19.
E(g)$Deal
#> [[1]]
#> [1] 14 19
#> 
#> [[2]]
#> [1] 18
#> 
#> [[3]]
#> [1] 15
#> 
#> [[4]]
#> [1] 17

推荐阅读