First, your code doesn't seem to work. I don't think you should group_by before applying the test, the grouping is specified by the formula.
Then, to put it inside a function, you can build your formula as a string and convert it with as.formula():
aaa <- function(dta, col){
dta %>%
rstatix::pairwise_t_test(as.formula(paste0(col," ~ Species")),
p.adjust.method = "bonferroni")
}
aaa(iris, "Sepal.Length")
Here this works because as.formula() is a base R function that doesn't use data masking. If you want to include a group_by(), you will need to take a look at this page that shows you how to call group_by({{ col}}).
So if you had 2 grouping variables:
#add other categorical column
iris2 <- iris %>%
add_column(other_cat = sample(1:5, nrow(iris), replace = TRUE))
aaa <- function(dta, col1, col2){
dta %>%
group_by({{col1}}) %>%
rstatix::pairwise_t_test(as.formula(paste0(col2," ~ Species")), p.adjust.method = "bonferroni")
}
# these 2 commands produce the same result
iris2 %>%
group_by(other_cat) %>%
rstatix::pairwise_t_test(Sepal.Length ~ Species, p.adjust.method = "bonferroni")
aaa(iris2, other_cat, "Sepal.Length")
Of course, once you have a function doing what you want to a column, you can apply it to all columns with a map-family function.