練習1:建立矩陣

#建立2X5矩陣
mat1 <- matrix(1:10, nrow = 2, ncol = 5)
#顯示矩陣
mat1
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    3    5    7    9
## [2,]    2    4    6    8   10
#使用 seq() 建立奇數矩陣

#方法1 指定步長(by = )
mat2_1 <- matrix(seq(1, 17, by = 2), nrow = 3, ncol = 3)
#顯示矩陣
mat2_1
##      [,1] [,2] [,3]
## [1,]    1    7   13
## [2,]    3    9   15
## [3,]    5   11   17
#取得對角線元素
diag(mat2_1)
## [1]  1  9 17
#方法2 指定長度(length.out = )
mat2_2 <- matrix(seq(1, 17, length.out = 9), nrow = 3, ncol = 3)
#顯示矩陣
mat2_2
##      [,1] [,2] [,3]
## [1,]    1    7   13
## [2,]    3    9   15
## [3,]    5   11   17
#取得對角線元素
diag(mat2_2)
## [1]  1  9 17

練習2:日常接觸

#載入 igraph 套件
library(igraph)
## 
## 載入套件:'igraph'
## 下列物件被遮斷自 'package:stats':
## 
##     decompose, spectrum
## 下列物件被遮斷自 'package:base':
## 
##     union
g=make_graph(~東-凱-定-書-東, 書-凱, 東-定, 詠-東,詠-凱, 詠-琪, 尤, 軒, 客服人員, 加油站人員, 超商店員 )
plot(g,
     vertex.label.cex = 1.2, 
     vertex.label.font = 2)

練習3:從矩陣到網絡圖

#載入 igraph 套件
library(igraph)

#設定隨機種子,確保結果可重現
set.seed(123)

#1. 建立 10x10 的隨機 0-1 矩陣
mat <- matrix(sample(0:1, 100, replace = TRUE), nrow = 10, ncol = 10)

#2. 將對角線元素設為 0
diag(mat) <- 0

#3. 將矩陣轉換為 igraph 物件
g <- graph_from_adjacency_matrix(mat, mode = "undirected")
## Warning: The `adjmatrix` argument of `graph_from_adjacency_matrix()` must be symmetric
## with mode = "undirected" as of igraph 1.6.0.
## ℹ Use mode = "max" to achieve the original behavior.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
#4. 繪製網絡圖
plot(g, 
     vertex.size = degree(g) *4,
     vertex.label.font = 2,
     vertex.label.cex = 1, 
     edge.width = 1.5, 
     edge.color = "gray")