0

I'm writing a function to add a kruskal-wallis test AND dunn test to ggplot. In particular, I would like the following function to also work with tibbles but it only works for dataframes

library(rstatix)
library(ggpubr)
library(tidyverse)

plot_w_dunn <- function(dat, xvar, yvar) {
  require("dplyr")
  dat$var1 <- dat[,yvar]
  dat$var2 <- dat[,xvar]
  dat$var2 <- factor(dat$var2)

  dunn_stat <- dat %>% dunn_test(var1 ~ var2, p.adjust.method = "hochberg")
  dunn_stat <- dunn_stat %>% add_xy_position(x = "var2")
  dunn_stat$p.adj.sci <- format(dunn_stat$p.adj, scientific = TRUE, digits = 3)
  dunn_stat
  print(dunn_stat)
  
  plot <- ggplot(dat, mapping = aes(x = var2, y = var1, fill = var1)) +
    geom_boxplot() +
    stat_compare_means(method = "kruskal.test", label.y = 45, hjust = 0.5) +
    stat_pvalue_manual(dunn_stat, label = "p.adj.sci", hide.ns = FALSE, inherit.aes = FALSE,
                       size = 3, step.increase = 0.05) +
    labs(x = xvar, y = yvar)
  return(plot)
  }

plot_w_dunn(as_tibble(mtcars), "cyl", "mpg") #gives error
plot_w_dunn(mtcars, "cyl", "mpg") #works
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Use `dat[[yvar]]` and `dat[[xvar]]` rather than `dat[,yvar]` and `dat[,xvar]`. tibbles do not simplify to vectors when subsetting by a single column using `[, ]` – MrFlick Jul 21 '22 at 15:16
  • 1
    You should almost always use `library`, not `require`. The latter never stops following code when the package is not available, which is almost never what is intended. Refs: https://stackoverflow.com/a/51263513. – r2evans Jul 21 '22 at 15:28
  • 1
    #gives error .... what error , please be a little more precise – user12256545 Jul 21 '22 at 17:23

0 Answers0