RStudioのmanipulate関数でグラフ描画にインタラクティブな操作を追加する(2)

イメージ 1 snaパッケージとmanipulate関数を使って、Watts & Strogatzモデルのスモールワールド・シミュレーションを可視化するコードです。

パラメータはスライダーでインタラクティブに操作できます。
Nでノード数、nearest_neighborで初期状態でいくつ隣りとリンクするか、rewiring_probabilityでリンクの掛け替え確率を設定します。

スライダーの設定の数値を変えればNをもっと大きくしたりできます。

library(sna)
library(manipulate)

clust.coeff <- function(matrix){
n <- nrow(matrix)
output <- rep(0,n)
for (i in 1:n){
m <- sum(matrix[i,])
output[i] <-
sum(t(matrix * matrix[i,]) * matrix[i,])/(m * (m - 1))
}
output[which(output == "NaN")] <- 0
output
}

manipulate(
gplot(graph <- rgws(1,N,1,nearest_neighbor,rewiring_probability), mode = "circle", gmode = "graph",jitter = FALSE,
xlab = paste("average shortest path length = ", round(mean(geodist(graph)$gdist[-c(which(geodist(graph)$gdist == 0),
which(geodist(graph)$gdist == Inf))]),2), " clustering coefficient = ",round(mean(clust.coeff(graph)),2))),
N = slider(10,100),
nearest_neighbor = slider(1,10),
rewiring_probability = slider(0,1)
)

※rewiring_probability = 0のときのレギュラーグラフはもともとのWatts & Strogatzモデルと違い、円環状ではなく帯状になりますが、これはsnaパッケージのrgws関数の仕様です(その方が平均距離が急激に低下するため)。