I have searched through the archives but have not found a suitable answer. I am a beginner and please excuse my ignorance if I am posing a very elementary query. I am trying to
Ok, this is old, but I came across the same problem and wanted to share my approach, although it violates to some extent the *apply idea. The upside is: you can integrate anything in the loop. So I needed to run an ANOVA on 2 output variables, depending on columns I looped through with lapply, get the p_values to annotate the plot and create multiple plots side-by-side. The core is that it combines a for-loop with lapply
for (i in 0:10){
i<-i+1
lapply(df[i],function(x) {
myfactor<-names(df)[i] #gets the column name
anova_model_a<-lm(a~x,df) #needed to run ANOVA per column
anova_model_b<-lm(b~x,df) #needed to run ANOVA per column
tab_aov_a<-tidy(summary(anova_model_a)) #proper result table
tab_aov_b<-tidy(summary(anova_model_b)) #proper result table
labels_a <- data.frame(drv = "1", label=c(round(tab_aov_a$p.value[2],4))) #needed for labelling the graph. I only had 2 groups for comparison
labels_b <- data.frame(drv = "1", label=c(round(tab_aov_b$p.value[2],4))) #needed for labelling the graph
fig1<-ggplot(df,aes(x,a))+
geom_boxplot()+
ggtitle("a")+
geom_text(data=labels_a,aes(x=drv,y=12,label=label),colour="blue",angle=0,hjust=0.5, vjust=0.5,size=5)+
xlab(myfactor)
fig2<-ggplot(df,aes(x,b))+
geom_boxplot()+
ggtitle("b")+
geom_text(data=labels_b,aes(x=drv,y=6,label=label),colour="blue",angle=0,hjust=0.5, vjust=0.5,size=5)+
xlab(myfactor)
arrangement<-grid.arrange(fig1,fig2,nrow=2)
print(arrangement)
})
}