R语言批量做单因素方差分析并作柱形图和误差线图

用R语言里自带的PlantGrowth数据集做测试
构造一个多变量的数据集
PlantGrowth %>%
select(2,1) %>%
rename(“A”=”weight”,
“treatment”=”group”) %>%
mutate(B=A,
D=A,
E=A,
G=A) %>%
rio::export(file = “D:/R_4_1_0_working_directory/env001/2024.data/20240906/dat.xlsx”)
假如自己的数据集需要批量做这个单因素方差分析的,把数据整理成如下格式

第一列是分组,后面每一列是一个变量,excel存储数据
读取数据

library(readxl)

read_excel(“D:/R_4_1_0_working_directory/env001/2024.data/20240906/dat.xlsx”) %>%
pivot_longer(!treatment,names_to = “group”) %>%
arrange(group) %>%
select(2,1,3) -> ano.dat
这里读取数据并将其整理成长格式数据

把数据按照变量列进行折叠
ano.dat %>%
nest(.by = “group”)

批量做 单因素方差分析

ano.dat %>%
nest(.by = “group”) %>%
mutate(aov_out=map(data,~aov(value~treatment,data=.))) %>%
mutate(tidy=map(aov_out,broom::tidy)) %>%
unnest(tidy)

批量做多重检验

library(tidyverse)
library(agricolae)
myfun<-function(x){ LSD.test(x,”treatment”,p.adj=”none”) %>%
.$groups %>%
rownames_to_column() -> tmp.dat.01
LSD.test(x,”treatment”,p.adj=”none”) %>%
.$means %>%
rownames_to_column() %>%
select(-value)-> tmp.dat.02

left_join(tmp.dat.01,tmp.dat.02,by=c(“rowname”=”rowname”))
}

ano.dat %>%
nest(.by = “group”) %>%
mutate(aov_out=map(data,~aov(value~treatment,data=.))) %>%
mutate(tidy=map(aov_out,broom::tidy)) %>%
mutate(lsd_out=map(aov_out,myfun)) %>%
unnest(lsd_out) %>%
select(group,rowname,value,groups,std)

这个就是用来作图的数据
批量作图

自定义一个画图函数

myplot<-function(mydat){ ylab<-mydat %>% pull(“name”) %>% unique()
mydat %>%
mutate(rowname=factor(rowname,levels=c(“ctrl”,”trt1″,”trt2″))) %>%
ggplot(aes(x=rowname,y=value))+
geom_col(aes(fill=rowname),
show.legend = FALSE)+
geom_errorbar(aes(ymin=value-std,
ymax=value+std),
width=0.2)+
geom_text(aes(y=value+std,label=groups),
vjust=-0.2,
size=5)+
theme_bw(base_size = 10)+
theme(panel.grid = element_blank())+
scale_fill_manual(values = c(“#009f73″,”#0072b1″,”#d55e00”))+
scale_y_continuous(expand = expansion(mult = c(0,0.15)))+
labs(x=NULL,y=NULL,title = ylab)
}

plot.data %>%
mutate(name=group) %>% ## 这里添加一列是用来给每个图添加一个title
nest(.by=”group”) %>%
mutate(plot_out=map(data,myplot)) %>%
pull(plot_out) %>%
patchwork::wrap_plots(nrow = 2)

这里误差线用的是平均值加减标准差

声明:文中观点不代表本站立场。本文传送门:https://eyangzhen.com/421190.html

联系我们
联系我们
分享本页
返回顶部