amikoma
amikoma

Reputation: 85

A lot of correlation test to do

I have df like this with 15 numeric column (values are random, not my real data):

Val(numeric):      val.2:              Val.3   ....   Val.15  
1.698              1.689               5.478           5.68
4.98               0.65                69.47           4.78
0.123              3                   12 .698         6.98
-----------------------------------------------------------
0.047              65.98               123.47          1.547

I calculated the correlation between each variable:

          val      val.2  ...  val.15                  
val       1        0.32         0.1256                  
val.2     0.9      1            0.125    
...
val.15    0.36    0.12          1               

But I want to do correlation Test ( cor.test() ) between each column. Is there a way to do it automatically instead of doing a lot of tests like:
cor.test(df$val, df$val.2, method = 'spearman')
cor.test(df$val, df$val.3, method = 'spearman')
...... etc.
cor.test(df$val.14, df$val.15, method = 'spearman')

Upvotes: 0

Views: 89

Answers (2)

Greg Snow
Greg Snow

Reputation: 49640

Any time you want to do something on all pairs (or other combinations), the combn function is one approach. It will create the pairs and optionally run a function on each pair:

> combn(1:4, 2, FUN=function(x) cor.test(iris[,x[1]], iris[,x[2]])$p.value)
[1] 1.518983e-01 0.000000e+00 0.000000e+00
[4] 4.513314e-08 4.073229e-06 0.000000e+00
> p.adjust(.Last.value)
[1] 1.518983e-01 0.000000e+00 0.000000e+00
[4] 1.353994e-07 8.146457e-06 0.000000e+00

Upvotes: 0

akrun
akrun

Reputation: 887193

You can try

library(Hmisc)
rcorr(as.matrix(df), type='spearman')$P

Upvotes: 1

Related Questions