Skip to content

Instantly share code, notes, and snippets.

@shirayuca
Created June 30, 2020 07:02
Show Gist options
  • Save shirayuca/85fd10233bd840ab83400e6fad6df179 to your computer and use it in GitHub Desktop.
Save shirayuca/85fd10233bd840ab83400e6fad6df179 to your computer and use it in GitHub Desktop.
情報学特殊講義A_08回(中心性、鈴木努『ネットワーク分析 第2版 (Rで学ぶデータサイエンス) 』共立出版、2017年参照)
# ライブラリの準備
install.packages("igraph")
library(igraph)
# データの準備
d <- read.csv("08_imotodesse.csv", header=T)
g <- graph.data.frame(d[1:2],directed=T)
### ネットワーク分析
# ノード数、リンク数
vcount(g)
# リンク数
ecount(g)
# 各ノードの入次数をdegree.csvに書き出す
write.csv(degree(g, mode = "in"), "degree_in.csv", fileEncoding = "CP932")
# 各ノードの出次数をdegree.csvに書き出す
write.csv(degree(g, mode = "out"), "degree_out.csv", fileEncoding = "CP932")
# 平均入次数(in、outのリンク数が同じのため、平均出次数も同じ値)
sum(degree(g, mode = "in"))/vcount(g)
# 平均経路長
average.path.length(g)
# dd.inにgの入次数分布を代入
dd.in <- degree.distribution(g, , mode = "in")
# ddの散布図を作成する。x軸ラベルは次数、y軸ラベルは出現確率。
plot(dd.in[-1],xlab="k",ylab="p(k)")
# dd.outにgの入次数分布を代入
dd.out <- degree.distribution(g, , mode = "out")
# ddの散布図を作成する。x軸ラベルは次数、y軸ラベルは出現確率。
plot(dd.out[-1],xlab="k",ylab="p(k)")
# 次数中心性
write.csv(degree(g, mode = "in") / (vcount(g) - 1), "degree_centrality_in.csv", fileEncoding = "CP932")
write.csv(degree(g, mode = "out") / (vcount(g) - 1), "degree_centrality_out.csv", fileEncoding = "CP932")
# 近接中心性(in:他のノードからの距離)
write.csv((vcount(g)-1) * closeness(g, mode="in"), "closeness_centrality_in.csv", fileEncoding = "CP932")
# 近接中心性(out:他のノードへの距離)
write.csv((vcount(g)-1) * closeness(g, mode="out"), "closeness_centrality_out.csv", fileEncoding = "CP932")
# 媒介中心性
write.csv(betweenness(g) / ((vcount(g)-1) * (vcount(g)-2)), "betweenness_centrality.csv", fileEncoding = "CP932")
# ネットワーク描画
png("graph.png", width=1200,height = 1000)
plot(g, vertex.size=degree(g)*0.2,edge.arrow.size=0.1, layout=layout.fruchterman.reingold)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment