R 编程/排序
外观
< 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 <- 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
在 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
chem_pca <- rda(varechem, scale = TRUE) # Run PCA
biplot(chem_pca, scaling = 2) # display biplot