rm(list=ls())#clear Global Environmentsetwd('D:\桌面\聚类分析')#设置工作路径
#安装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=" ",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格式文件
更多精彩欢迎大家关注微信公众号【科研后花园】!!!
留言与评论(共有 0 条评论) “” |