-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathX01_GraphPageRank.R
executable file
·100 lines (84 loc) · 2.63 KB
/
X01_GraphPageRank.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# =======================================================
# PageRank computation on a Graph
# =======================================================
#install.packages("igraph")
library(igraph)
# Adjacency matrix for the example graph
adjMat <- rbind(
c(0,1,1,0,0,0,0),
c(1,0,1,1,0,0,0),
c(1,1,0,0,0,0,0),
c(0,1,0,0,1,1,1),
c(0,0,0,1,0,1,0),
c(0,0,0,1,1,0,1),
c(0,0,0,1,0,1,0))
# Creating a graph object from the adjacency matrix
g <- graph.adjacency(adjMat, mode = "undirected")
plot(g, layout = layout.fruchterman.reingold,
vertex.size = 25,
vertex.color="red",
vertex.frame.color= "white",
vertex.label.color = "white",
vertex.label.family = "sans",
edge.width=2,
edge.color="black")
# -------------------------------------------------------
# Compute PageRank on the graph
# Compute the Transition Matrix for Random Walk
transMat <- t(adjMat / rowSums(adjMat))
transMat
# Compute the principal eigenvector of transMat
transEig <- eigen(transMat)
transEig
pageRank <- transEig$vec[,1]
pageRank
# Normalized PageRank
npageRank <- pageRank / sum(pageRank)
npageRank
# Represent PageRank as size of vertices
V(g)$size <- 25 + 100 * round(npageRank[V(g)], 2)
plot(g, layout = layout.fruchterman.reingold,
vertex.size = V(g)$size,
vertex.color="red",
vertex.frame.color= "white",
vertex.label.color = "white",
vertex.label.family = "sans",
edge.width=2,
edge.color="black")
# -------------------------------------------------------
# Shortcut : Use the stock pagerank function in R
npageRank <- page.rank(g)
npageRank
V(g)$size <- 25 + 100 * round(npageRank$vector[V(g)], 2)
plot(g, layout = layout.fruchterman.reingold,
vertex.size = V(g)$size,
vertex.color= "red",
vertex.frame.color= "white",
vertex.label.color = "white",
vertex.label.family = "sans",
edge.width=2,
edge.color="black")
# -------------------------------------------------------
# Example graph: Zachary's Karate Club
g <- make_graph("Zachary")
plot(g, layout = layout.fruchterman.reingold,
vertex.size = 10,
vertex.label = NA,
vertex.color="red",
vertex.frame.color= "white",
vertex.label.color = "white",
vertex.label.family = "sans",
edge.width=2,
edge.color="black")
npageRank <- page.rank(g)
npageRank
V(g)$size <- 10 + 100 * round(npageRank$vector[V(g)], 2)
plot(g, layout = layout.fruchterman.reingold,
vertex.size = V(g)$size,
vertex.label = NA,
vertex.color="red",
vertex.frame.color= "white",
vertex.label.color = "white",
vertex.label.family = "sans",
edge.width=2,
edge.color="black")