compare_means is a straightforward function which I consider very useful:
library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
res <- compare_means(len ~ supp,
group.by = "dose",
data = df,
method = "wilcox.test", paired = FALSE)
However, to the best of my knowledge, it is not possible to obtain means and standard deviations (or standard errors) in the relative table of results.
> res
# A tibble: 3 × 9
dose .y. group1 group2 p p.adj p.format p.signif method
<dbl> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr>
1 0.5 len OJ VC 0.0232 0.046 0.023 * Wilcoxon
2 1 len OJ VC 0.00403 0.012 0.004 ** Wilcoxon
3 2 len OJ VC 1 1 1.000 ns Wilcoxon
>
Which is the best way to obtain group 1 and group 2 means and SD/SE with few code lines? I would like to have means (SD) instead of groups' labels OJ/VC.
Based on the documentation, there are no specific arguments helpful to this aim.
UPDATE with my dirty dirty way:
library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
p <- ggbarplot(df, x = "supp", y = "len",
add = c("mean_sd"),
facet.by = "dose",
position = position_dodge(0.8))+
stat_compare_means(method = "wilcox.test", paired = FALSE)
# Extracting all ggplot infos
my_data <- ggplot_build(p)
# Extracting means and Standard Deviations from the plot
my_means_sd <- (my_data[["data"]][[2]])[,1:5]
my_means_sd$labs <- paste0(my_means_sd$y,
" (",
round(my_means_sd$ymin, 1),
"-",
round(my_means_sd$ymax, 1),
")")
my_means_sd <- my_means_sd[,c("x", "labs")]
# Manipulating dataframe
library(dplyr)
my_means_sd <- as.data.frame(my_means_sd %>%
group_by(x) %>%
mutate(row = row_number()) %>%
tidyr::pivot_wider(names_from = x, values_from = labs) %>%
select(-row) )
# Extracting P values from plot
my_pvalues <- (my_data[["data"]][[3]])[,9:13]
res <- cbind(my_means_sd, my_pvalues)
The result I generated:
> res
1 2 p p.adj p.format p.signif method
1 13.23 (8.8-17.7) 7.98 (5.2-10.7) 0.023186427 0.023 0.023 * Wilcoxon
2 22.7 (18.8-26.6) 16.77 (14.3-19.3) 0.004030367 0.004 0.004 ** Wilcoxon
3 26.06 (23.4-28.7) 26.14 (21.3-30.9) 1.000000000 1.000 1 ns Wilcoxon
>