简体   繁体   English

在R中使用有向边生成图形

[英]Building a Graph with Directed Edges in R

I have a Dataset which looks like this: 我有一个数据集,看起来像这样:

PostID UserID ReplyTo
1      11     NA
2      12     1
3      11     2
4      13     NA
5      12     4

I want to have a directed Graph with the Edges: 12->11, 11->12, 12->13 我想有一个有边的有向图:12-> 11,11-> 12,12-> 13

The Idea is that ad the End i'm capable of having a list of UserID's to which i add the Different Centralities. 想法是,广告End我能够拥有一个UserID列表,并向其中添加不同的Centrality。

The way i tried it i was only capable of producing a graph between the PostID's and not the UserID's. 我尝试的方式只能在PostID而非UserID之间生成图形。

library(igraph)

D <- data.frame(Data$PostID, Data$ReplyTo)
FinalEdges<-D[complete.cases(D),]
FinalNetwork <- graph.data.frame(FinalEdges, directed = TRUE)


plot(FinalNetwork, vertex.label = V(FinalNetwork)$PostID) 

For the Different Centralities i use: 对于不同的中心,我使用:

DegreeCentrality<-degree(FinalNetwork)
ClosenessCentrality<-closeness(FinalNetwork)
BetweennessCentrality<-betweenness(FinalNetwork)
which i the would like to add to a list of users.

At The End i would like to have A List of Users and their Centralities 最后,我希望有一份用户列表及其中心

UserID, DegreeCentrality, Closeness Centrality, BetweennessCentrality
11
12
13

You'll need to reshape your input data to connect the pairs. 您需要重塑输入数据的形状以连接线对。 If this is your sample input data 如果这是您的样本输入数据

dd<-structure(list(PostID = 1:5, UserID = c(11L, 12L, 11L, 13L, 12L
), ReplyTo = c(NA, 1L, 2L, NA, 4L)), .Names = c("PostID", "UserID", 
"ReplyTo"), class = "data.frame", row.names = c(NA, -5L))

Then you can merge the replies with 然后,您可以将回复与

 mm<-merge(dd, dd, by.x="ReplyTo", by.y="PostID")

This produces 这产生

  ReplyTo PostID UserID.x UserID.y ReplyTo
1       1      2       12       11      NA
2       2      3       11       12       1
3       4      5       12       13      NA

as well as a warning that the ReplyIo column is repeated. 以及对ReplyIo列重复的警告。 But that's not really a problem. 但这不是真正的问题。 We just need the two UserID columns. 我们只需要两个UserID列。 We can turn those into a graph 我们可以将它们变成图表

library(igraph)
gg <- graph.data.frame(mm[,c("UserID.x","UserID.y")])

在此处输入图片说明

With that object you should be able to use the igraph library to calculate whatever statistics you want. 使用该对象,您应该能够使用igraph库计算所需的统计信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM