跳轉到內容

R 程式設計/網路分析

來自華夏公益教科書,開放的書籍,為開放的世界

R 程式設計/分析

我們主要使用以下軟體包來演示 R 中的網路分析:statnetsnaigraph。但它們並非完整列表。有關完整列表,請參見 gR 任務檢視,R 中的圖形模型

使用 igraph 建立簡單圖形

[編輯 | 編輯原始碼]
 
> # load the appropriate library
> library(igraph)
> # now create a few simple graphs
> # an undirected graph with 10 nodes and without any edge
> g1 <- graph.empty(10,directed=FALSE)
> # a directed graph with 10 nodes
> g2 <- graph.ring(10,directed=TRUE)
> # a complete undirected graph with 10 nodes
> g3 <- graph.full(10,directed=FALSE)
> # now get information about these graphs
> summary(g1)
> # g1 is an igraph object, U = Undirected, with 10 nodes and 0 edge
> IGRAPH U--- 10 0 -- 
> summary(g2)
> # g1 is an igraph object,  D = Directed
> IGRAPH D--- 10 10 -- Ring graph

從資料建立圖形

[編輯 | 編輯原始碼]

首先載入 igraph 包

library(igraph)

然後您可以選擇您喜歡的格式。以下是作為邊列表和鄰接矩陣提供的資料示例。

從邊列表建立圖形

[編輯 | 編輯原始碼]

邊列表由一個兩列矩陣形成,每行定義一條邊。從第一列中的每個元素到第二列中的對應元素繪製一條邊。使用 graph.edgelist() 函式匯入您的資料。

 
# producing some random data in edge list form
el <- cbind(sample(1:10, 10), sample(1:10, 10))

# creating and plotting the graph from the edge list
gr <- graph.edgelist(el)
plot(gr)

從鄰接矩陣建立圖形

[編輯 | 編輯原始碼]

鄰接矩陣是一個 n × n 矩陣,包含 n 個頂點,其中每個條目 aij 表示從頂點 i 到頂點 j 的邊數。要匯入您的鄰接矩陣,請使用 graph.adjacency() 函式。

 
# producing a random adjacency matrix
adj <- matrix(sample(0:1, 100, replace=T), 10, 10)

# creating and plottig the graph from the adjacency matrix
gr <- graph.adjacency(adj)
plot(gr)

參考文獻

[編輯 | 編輯原始碼]
上一頁:因子分析 索引
華夏公益教科書