I have a data frame with one grouping factor (the first column) with multiple levels (more than two) and several columns with data. I want to apply the wilcox.test
You can loop over the columns using apply
and then pass the columns to whatever test you want to use using an anonymous function, like so (assuming the data frame is named df
):
apply(df[-1],2,function(x) kruskal.test(x,df$group))
Note: I used the Kruskal-Wallis test because that works on multiple groups. The above would work just as well using the Wilcoxon test if there were only two groups.
If you do want to do pairwise Wilcoxon tests on all variables, here's a two-liner that will loop through all columns and all pairs and return the results as a list:
group.pairs <- combn(unique(df$group),2,simplify=FALSE)
# this loops over the 2nd margin - the columns - of df and makes each column
# available as x
apply(df[-1], 2, function(x)
# this loops over the list of group pairs and makes each such pair
# available as an integer vector y
lapply(group.pairs, function(y)
wilcox.test(x[df$group %in% y],df$group[df$group %in% y])))