Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert formula equation for functions in R (wilcox test) etc?

I’m trying to make a function to accept different formula groups for the wilcox test. I do not understand how to change the formula equation to make it modular.

Example below:

library(rstatix)
library(dplyr)
data("ToothGrowth")
df <- ToothGrowth

df %>%
      group_by(dose) %>%
      wilcox_test(data =., len ~ supp) %>%
      adjust_pvalue(method = "bonferroni") %>%
      add_significance("p.adj")


# This Does Not Work

wilcox_test2 <- function(df,x,y){
return(df %>%
  group_by(dose) %>%
  wilcox_test(data =., x ~ y) %>%
  adjust_pvalue(method = "bonferroni") %>%
  add_significance("p.adj"))

}

wilcox_test2(df,df$len,df$supp)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could pass the column names as argument and create the formula wihtin the function using reformulate

library(dplyr)
library(rstatix)
wilcox_test2 <- function(df, x, y){

 df %>%
   group_by(dose) %>%
   wilcox_test(data =., reformulate(y, response = x) ) %>%
   adjust_pvalue(method = "bonferroni") %>%
   add_significance("p.adj")

}

-testing

> wilcox_test2(df, "len", "supp")
# A tibble: 3 × 10
   dose .y.   group1 group2    n1    n2 statistic       p  p.adj p.adj.signif
* <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl>   <dbl>  <dbl> <chr>       
1   0.5 len   OJ     VC        10    10      80.5 0.0232  0.0696 ns          
2   1   len   OJ     VC        10    10      88.5 0.00403 0.0121 *           
3   2   len   OJ     VC        10    10      49.5 1       1      ns          
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading