基于R语言的微生物群落组成多样性分析——聚类分析
2022-08-07 本文已影响0人
科研那点事儿
一、工作目录设置
rm(list=ls())#clear Global Environment
setwd('D:\\桌面\\聚类分析')#设置工作路径
二、R包的安装与加载
#安装R包
# install.packages("vegan")
# install.packages("ape")
# install.packages("phangorn")
#加载所需R包
library(vegan)
library(ape)
library(phangorn)
三、加载数据
加载的数据同样是列为样本名、行为OTU的OTU表格:
df <- read.table("OTU.txt",sep="\t",header=T,check.names=F ,row.names=1)

四、计算距离矩阵
使用vegan包中的vegdist()函数计算距离矩阵,方法默认选择bray curtis:
df_dist <- vegdist(t(df),method = 'bray')#使用bray curtis方法计算距离矩阵

五、常规层次聚类
1、层次聚类
使用ape包中的hclust()函数进行层次聚类,可选择方法有single、complete、median、mcquitty、average 、centroid 、ward:
df_hc1 <- hclust(df_dist,method="average")#使用类平均法进行聚类
2、可视化
plot(as.dendrogram(df_hc1),type="rectangle",horiz=T)

3、将数据保存为newick格式
#将数据导出为newick格式文件
df_tree <- as.phylo(df_hc1)# 将聚类结果转成系统发育格式
write.tree(phy=df_tree, file="tree.nwk") # 输出newick格式文件
六、利用非加权组平均法进行层次聚类
1、使用phangorn包中的upgma函数进行层次聚类
##使用非加权组平均法(unweighted pair-group method with arithmetic means, UPGMA)进行层次聚类
df_hc2 <- upgma(df_dist)
2、可视化
#图形展示类型共有"phylogram"、"cladogram"、"fan"、"unrooted"、"radial"、"tidy"六种,默认为"phylogram"
plot(df_hc2, type="phylogram")
plot(df_hc2, type="cladogram")
plot(df_hc2, type="fan")
plot(df_hc2, type="unrooted")
plot(df_hc2, type="radial")
plot(df_hc2, type="tidy")

3、将数据保存为newick格式
df_tree <- as.phylo(df_hc2)# 将聚类结果转成系统发育格式
write.tree(phy=df_tree, file="tree.nwk") # 输出newick格式文件