#加载需要用到的包
#利用vegan包实现抽平分析的方法
library(vegan)
#加载工作目录
directory ="~/工作目录"
setwd(directory)
#加载otu表
otu <- read.csv("~.csv")
x <- otu[,c(2:8)]
#求和查看每个样本的和
colSums(x)
#使用该代码进行抽平
otu_Flat = as.data.frame(t(rrarefy(t(x), min(colSums(x)))))
#查看抽平后的每个样本的和
colSums(otu_Flat)
# 将抽平后的otu表保存到该工作目录,准备后面的多样性分析
write.csv(otu_Flat, file ="otu_Flat.csv",row.names = T)
otu <- read.csv("otu_Flat.csv")
colnames(otu)
y <- otu[,c(2:8)]
y <- t(y)
#定义函数进行计算
alpha_diversity <- function(x) {
observed_species <- estimateR(x)[1,]
Chao1 <- estimateR(x)[2,]
ACE <- estimateR(x)[4,]
Shannon <- diversity(x, index='shannon', base=2)
Simpson <- diversity(x, index='simpson')
goods_Coverage <- 1 - rowSums(x == 1) / rowSums(x)
Shannon <- sprintf("%0.4f", Shannon)
Simpson <- sprintf("%0.4f", Simpson)
goods_Coverage <- sprintf("%0.4f", goods_Coverage)
result <- data.frame(observed_species, Chao1, ACE, Shannon, Simpson, goods_Coverage)
}
alpha <- alpha_diversity(y)
得到结果~