[英]R - Directed graph, Keep only when directed both ways
I have a dataset of people that "like" each other.我有一个“喜欢”彼此的人的数据集。 I converted it to a graph.
我将其转换为图形。
g.likes <- graph_from_data_frame(dt.likes, directed = TRUE)
But I need to filter out the people that have liked each other.但是我需要过滤掉那些互相喜欢的人。 so only keep if A->B and B->A.
所以只在 A->B 和 B->A 时保留。
I don't seem to be able to find how I can do this.我似乎无法找到如何做到这一点。
Thank you in advance先感谢您
IGRAPH 80b2ed9 DN-- 15060 2577550 --
+ attr: name (v/c), week (e/n)
+ edges from 80b2ed9 (vertex names):
[1] 4 ->75 217->68 217->72 217->127 221->68 221->72 221->127 217->9 258->89 258->4 217->69 258->293 309->193
[14] 309->268 323->396 274->396 274->193 381->36 381->396 381->4 381->17 381->101 381->193 515->490 262->396 480->527
[27] 451->421 451->484 451->301 262->407 262->480 262->96 262->217 262->490 262->314 262->28 262->473 262->193 262->281
[40] 262->642 262->172 262->409 262->582 262->289 262->558 262->303 262->280 262->627 262->635 262->138 262->364 262->565
[53] 262->550 262->543 262->535 262->609 262->411 262->574 262->566 262->102 262->618 262->581 262->408 262->419 262->584
[66] 262->89 262->467 262->594 262->580 262->226 262->575 262->472 262->569 262->557 262->532 262->525 262->445 262->382
[79] 262->540 262->511 262->529 262->66 262->486 262->510 262->516 262->48 262->503 262->504 262->454 262->488 262->506
[92] 262->495 262->416 262->497 262->494 262->499 262->496 262->492 262->493 262->484 262->392 262->336 262->485 262->204
You can do this by altering the adjacency matrix of the graph (you can do it other ways too but this is straightforward).您可以通过改变图形的邻接矩阵来做到这一点(您也可以通过其他方式做到这一点,但这很简单)。
# Load the igraph package
library(igraph)
# make a toy graph to demonstrate
admat <- matrix(c(0,1,0,1,0,1,0,0,0), nrow=3)
g.likes <- graph_from_adjacency_matrix(admat, mode = 'directed')
plot(g.likes)
# if A -> B and B -> A that implies that the (i,j)th entry
# of the adjacency matrix is equal to the (j,i)th entry,
# (assuming that edges are binary and not real-valued)
# running the code starting from here on your own matrix will
# do what you want.
admat2 <- as_adjacency_matrix(g.likes, sparse = FALSE)
admat2 <- admat2 * t(admat2)
# now convert back to a graph structure
g.likes2 <- graph_from_adjacency_matrix(admat2, mode = 'directed')
plot(g.likes2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.