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)
CodePudding user response:
Another way is to pass the formula as one object:
wilcox_test3 <- function(df, form){
return(df %>%
group_by(dose) %>%
wilcox_test(data =., form) %>%
adjust_pvalue(method = "bonferroni") %>%
add_significance("p.adj"))
}
wilcox_test3(df, len ~ supp)
# A tibble: 3 x 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
CodePudding user response:
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