Skip to content

Instantly share code, notes, and snippets.

@shirayuca
Last active June 8, 2021 13:18
Show Gist options
  • Save shirayuca/e5b14794d104be666d76c556902195c9 to your computer and use it in GitHub Desktop.
Save shirayuca/e5b14794d104be666d76c556902195c9 to your computer and use it in GitHub Desktop.
##### パッケージの準備
# igraph、linkcommパッケージをインストール
install.packages("igraph")
install.packages("linkcomm")
# igraph、linkcommライブラリを読み込み
library(igraph)
library(linkcomm)
##### データの準備
# work_2.csvを読み込み、 dというオブジェクトに代入。1行目はヘッダー。
d <- read.csv("work_2.csv", header=T)
# igraphの関数graph.data.frameを使って、dの1-2列目をネットワークグラフのオブジェクトgに変換。directedは向きを表し、無向はF、有向はT。
g <- graph.data.frame(d[1:2],directed=T)
##### ノード数、リンク数、次数、平均経路長
# ノード数、リンク数
vcount(g)
# リンク数
ecount(g)
# 各ノードの入次数をdegree_in.csvに書き出す
write.csv(degree(g, mode = "in"), "degree_in.csv", fileEncoding = "CP932")
# 各ノードの出次数をdegree_out.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)")
##### クラスター係数
# 局所クラスター係数をlocal_c.csvに書き出す(ラベルの出力ができないため、degree.csvのラベルと合わせて確認)
write.csv(transitivity(g, type="local",isolates="zero"), "local_c.csv", fileEncoding = "CP932")
# 平均クラスター係数
transitivity(g, type="global")
##### 中心性を算出
# 次数中心性
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")
##### コミュニティの抽出
gg <- d[1:2]
# 分割密度が最大になるようなリンクコミュニティの分割
lc <- getLinkCommunities(gg, directed = T)
# 結果の出力
print(lc)
# 各ノードがどのリンクコミュニティに属するかを出力
write.csv(lc$nodeclusters, "community.csv", fileEncoding = "CP932")
##### 可視化(参考程度)
# ネットワーク図としてプロット
plot(g,layout=layout.auto, vertex.size=5, edge.arrow.size=.4)
mkdir ~/tmp
cd ~/tmp
curl -O -L https://moji.or.jp/wp-content/ipafont/IPAexfont/IPAexfont00401.zip
unzip IPAexfont00401.zip
mkdir -p ~/.fonts/ipa
cp ./IPAexfont00401/*.ttf ~/.fonts/ipa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment