【R语言 社交网络】R语言关系网络图+ PageRank算法实现

例子1:
library(plyr)

set.seed(10)
rm(list=ls())
library(igraph)
g<-random.graph.game(n=10,p.or.m=1/3,directed=TRUE)
com = walktrap.community(g, steps = 6)
V(g)$sg = com$membership + 1
V(g)$color = rainbow(max(V(g)$sg))[V(g)$sg]
plot(g, layout=layout.fruchterman.reingold,edge.color = grey(0.4),edge.arrow.mode = ">",vertex.size =20,
vertex.color = V(g)$color)
pr<-page.rank(g)$vector
df<-data.frame(Object=1:10,PageRank=pr)
arrange(df,desc(PageRank))


> arrange(df,desc(PageRank))
Object PageRank
1 3 0.18639194
2 6 0.13309889
3 1 0.12880261
4 9 0.12245781
5 4 0.11631227
6 2 0.08930467
7 10 0.08382175
8 8 0.05271135
9 5 0.04969638
10 7 0.03740232

这里写图片描述

例子2:

rm(list=ls())
library(igraph)
library(plyr)
#1.用igraph创建图表
g<- graph(c(1,2,1,3,1,4,2,3,2,4,3,4,4,2), directed=T)


com = walktrap.community(g, steps = 6)
V(g)$sg = com$membership + 1
V(g)$color = rainbow(max(V(g)$sg))[V(g)$sg]
plot(g, layout=layout.fruchterman.reingold,edge.color = grey(0.4),edge.arrow.mode = ">",vertex.size =20,
vertex.color = V(g)$color)


pr<-page.rank(g)$vector
df<-data.frame(Object=1:4,PageRank=pr)
arrange(df,desc(PageRank))


Object PageRank
1 4 0.3824972
2 2 0.3732476
3 3 0.2067552
4 1 0.0375000

例子2方法2:

rm(list=ls())
library(plyr)
pages<-read.table("F:\\page.txt",sep=",")
names(pages)<-c("src","dist")


#直接计算矩阵特征值
calcEigenMatrix<-function(G){
x <- Re(eigen(G)$vectors[,1])
x/sum(x)
}


#构建邻接矩阵
adjacencyMatrix<-function(pages){
n<-max(apply(pages,2,max))
A <- matrix(0,n,n)
for(i in 1:nrow(pages)) A[pages[i,]$dist,pages[i,]$src]<-1
A
}
#变换概率矩阵,考虑d的情况
dProbabilityMatrix<-function(G,d=0.85){
cs <- colSums(G)
cs[cs==0] <- 1
n <- nrow(G)
delta <- (1-d)/n
A <- matrix(delta,nrow(G),ncol(G))
for (i in 1:n) A[i,] <- A[i,] + d*G[i,]/cs
A
}


A<-adjacencyMatrix(pages)
G<-dProbabilityMatrix(A)
q<-calcEigenMatrix(G)
df<-data.frame(Object=1:length(q),PageRank=q)
arrange(df,desc(PageRank))

> arrange(df,desc(PageRank))
Object PageRank
1 4 0.3824972
2 2 0.3732476
3 3 0.2067552
4 1 0.0375000
>
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页