Starting with some dummy data
mdf <- data.frame( x1 = rnorm(5), x2 = rnorm(5), x3 = rnorm(5) )
I would firstly determine the combinations of interest. So if I understood you right the result of your calculation should be the same for mdf[c(i,j)]
and mdf[c(j,i)]
. in this case you could use the combn
function, to determine the relevant pairs.
pairs <- as.data.frame( t( combn( colnames( mdf ),2 ) ) )
pairs
V1 V2
1 x1 x2
2 x1 x3
3 x2 x3
Now you can just apply your function row-wise over the pairs (using a t.test here for simplicity):
pairs[["p.value"]] <- apply( pairs, 1, function( i ){
t.test( mdf[i] )[["p.value"]]
})
pairs
V1 V2 p.value
1 x1 x2 0.5943814
2 x1 x3 0.7833293
3 x2 x3 0.6760846
If you still need your p.values back in (upper triangular) matrix form you can cast them:
library(reshape2)
acast( pairs, V1 ~ V2 )
x2 x3
x1 0.5943814 0.7833293
x2 NA 0.6760846