跳轉到內容

R 程式設計/排序

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

此頁面提供了建立 距離矩陣 和執行和繪製 非度量多維標度 (NMDS) 排序的基本程式碼。

在維基百科上了解更多關於 排序 的資訊。

此程式碼依賴於 Jari Oksanen 在 R 中編寫的 vegan 包。 Jari Oksanen.

首先,匯入資料並載入所需的庫

require(MASS)
require(vegan)
data(varespec)   # species data
data(varechem)   # environmental data

距離矩陣

[編輯 | 編輯原始碼]
bray <- vegdist(varespec, method = "bray")				# calculate a distance matrix

# There are many distance measure options for 'dist', 
# discoverable by running '?dist'. Common distance measures include:
       # 'bray' = Bray-Curtis
       # 'canb' = Canberra
       # 'euclidean' = Euclidean

非約束排序

[編輯 | 編輯原始碼]

使用 NMDS 顯示差異性

[編輯 | 編輯原始碼]

NMDS 分析和繪圖

nmds <- metaMDS(varespec, k = 2, 
          distance = 'bray', autotransform = FALSE) 	# semi-black box NMDS function

ordiplot(nmds, type = "text")			      # Plot NMDS ordination
fit <- envfit(nmds, varechem[ ,1:4])			   # Calculates environmental vectors
fit						        # Lists vector endpoint coordinates and r-squared values
plot(fit)						   # adds environmental vectors
# a linear representation of environmental variables is not always appropiate
# we could also add a smooth surface of the variable to the plot
ordisurf(nmds, varechem$N, add = TRUE, col = "darkgreen")
nmds$stress                                             # stress value
生成的 nmds 圖


在 metaMDS 函式中,k 是使用者定義的,它與將投影限制在 k 維時投影擬合數據框的難易程度相關。傳統觀點認為應力不應超過 10-12%。應力可以透過增加維度來降低。但是,增加維度可能會降低二維圖中前兩個 NMDS 軸的“真實性”。


我們還可以執行一個具有 3 維的 nMDS,擬合環境向量並建立一個動態圖形

nmds3d <- metaMDS(varespec, k = 3, 
  distance = 'bray', autotransform = FALSE)              # run nmds with 3 dimensions
nmds3d$stress                                            # stress drops
fit3d <- envfit(nmds3d, varechem[ ,1:4], choices = 1:3)  # fit environmental vectors to 3d space
ordirgl(nmds3d, envfit = fit3d)                          # dynamic 3D graph

對環境資料執行主成分分析 (PCA)

[編輯 | 編輯原始碼]
chem_pca <- rda(varechem, scale = TRUE)    # Run PCA
biplot(chem_pca, scaling = 2)              # display biplot
PCA 雙標圖

約束排序

[編輯 | 編輯原始碼]
華夏公益教科書