今天小果通过这一篇文章带大家学会和了解双因素方差分析(ANOVA),话不多说,请看下面代码:
- 安装需要的R包
install.packages(“ggplot2”)
install.packages(“tidyverse”)
install.packages(“multcompView”)
install.packages(“ggsci”)
- 载入需要的R包
library(ggplot2)
library(tidyverse)
library(multcompView)
library(ggsci)
- 代码展示
soil <- read.table(file=”soil.txt”, sep = ‘\t’, header = TRUE)
group <- read.table(file=”group.txt”, sep = ‘\t’, header = TRUE)
#左连接合并两个文件
soil <- left_join(soil, group, by = ‘sample’)
#筛选需要的列
chao1 <- select(soil ,c(‘sample’, ‘treat’, ‘times’, ‘chao1’))
#将这两个因素类型(trate和times)改为因子
chao1$treat <- factor(chao1$treat)
chao1$times <- factor(chao1$times)
#双因素方差分析
anova<- aov(chao1~treat*times, data = chao1)
#计算mean和sd(分组统计mean和times)
dt <- chao1 %>% group_by(treat,times) %>%
summarise(w=mean(chao1), sd = sd(chao1)) %>%
arrange(desc(w)) %>%
ungroup()
#多重配对比较
cld <- TukeyHSD(anova) %>% multcompLetters4(anova,.)
le <- as.data.frame.list(cld$`treat:times`)
#获取字母标记
dt$Tukey <- le$Letters
#开始绘制带有显著性字母标记的柱状图
ggplot(dt, aes(times, w)) +
geom_bar(stat = “identity”,aes(fill=times),show.legend = FALSE,width=0.5) +
geom_errorbar(aes(ymin = w-sd, ymax=w+sd), width = 0.1) +
geom_text(aes(label = Tukey, y = w + sd), vjust = -0.5)+
facet_wrap(~treat)+
scale_fill_npg()+
labs(x=””,y=””)+
theme_test()+
theme(panel.background = element_blank(),
axis.line = element_line(color = “black”),
axis.text = element_text(size = 10,color = “black”),
axis.text.y = element_text(size = 10),
axis.ticks.x = element_blank())
最终通过一个示例数据进行了双因素方差分析,今天小果的分享就到这里奥,下期再见。