Solution for R ggplot and ggpubr, How to calculate/show p-values in facet_wrap graphs, with different groups in different graphs?

is Given Below:

I’m trying to wright the function that would graph my data. Data summarizes the value measurement after treatment from a few experiments in control vs treated group. Treatments might be different in different experiments. I’d like to get the graph comparing hand by hand different experiments (by facetting) and also showing p-values for pairwise comparison of the control group with different treatments.

Here is an expample:

```
set.seed(1)
library(ggplot2)
library(ggpubr) ## calculates the statistics for the graph
library(dplyr)
##creating dataset
exp1<-data.frame(exp = "exp1",
treatment = rep(c("control", "drug A", "drug B", "drug C"), 10),
result = runif(40, min =1, max = 10))
exp2<-data.frame(exp = "exp2",
treatment = rep(c("control", "drug A"), 10),
result = runif(20, min =1, max = 10))
exp3<-data.frame(exp = "exp3",
treatment = rep(c("control", "drug A", "drug C"), 10),
result = runif(30, min =1, max = 10))
data<-bind_rows(exp1, exp2, exp3)
##function for graphing the data
graph<-function(data, col_Name) {
treatment<-as.character(unique(data$treatment)) ## in the real dataset the treatment is an ordered factor, so use as.character here
g<-ggplot(data, aes(x=treatment, y = data[,col_Name], fill = treatment)) +
geom_boxplot(color = "black", alpha = 0.3)+
geom_dotplot(binaxis = "y", stackdir = "center", dotsize = 2, color = "black") +
facet_wrap(~exp, nrow = 1)+ #facetting the data
stat_compare_means(method = "t.test", aes(label = ..p.format..),
comparisons = mapply(c, "control", treatment[2:length(treatment)], SIMPLIFY = F) ) ### with mapply I create the list of pairwise comparisons I want to have
return(g)
}
graph(data, "result")
```

[![enter image description here][1]][1]

That’s what I’m getting so far:

[1]: https://i.stack.imgur.com/3qJnd.png

The problem is that it’s showing the statistics only when there are all 4 groups in the experiment. I’d like the function somehow for any given facet (meaning for every individual experiment) skip the groups missing the data in this exp, graph the groups with data and calculate statistics for pairwise comparisons with control group.

I’m wondering how to specify/skip groups with missing data specifically for every facet in order to show statistics in each of them ?

Thanks a lot!

Best!