3

I have two matrices of equal dimensions (p and e) and I would like to make a spearman correlation between columns of the same name. I want to have the output of pair correlations in a matrix (M)

I used the corr.test() function from library Psych and here is what I did:

library(psych) M <- data.frame(matrix(ncol=3,nrow=ncol(p))) M[,1] <- as.character() G <- colnames(p) for(rs in 1:ncol(p){ M[rs,1] <- G[rs] cor <- corr.test(p[,rs],e[,rs],method="spearman",adjust="none") M[rs,2] <- cor$r M[rs,3] <- cor$p } 

But I get an error message:

Error in 1:ncol(y) : argument of length 0 

Could you please show me what is wrong? or suggest another method?

1
  • @thelatemail has the proper solution; but in your code what would work is to change your corr.test line with corr.test(as.data.frame(p[,rs]), as.data.frame(e[,rs]), method="spearman", adjust="none"). The hint for this, from the error message, is that the function expects to have a two-dimensional data structure as x/y arguments. Commented Mar 16, 2015 at 4:32

2 Answers 2

7

No need for all this looping and indexing etc:

# test data p <- matrix(data = rnorm(100),nrow = 10) e <- matrix(data = rnorm(100),nrow = 10) cor <- corr.test(p, e, method="spearman", adjust="none") data.frame(name=colnames(p), r=diag(cor$r), p=diag(cor$p)) # name r p #a a 0.36969697 0.2930501 #b b 0.16363636 0.6514773 #c c -0.15151515 0.6760652 # etc etc 

If the names of the matrices don't already match, then match them:

cor <- corr.test(p, e[,match(colnames(p),colnames(e))], method="spearman", adjust="none") 
Sign up to request clarification or add additional context in comments.

Comments

1

Since the two matrices are huge, it would take very long system.time to execute the function corr.test() on all possible pairs but the loop that finally worked is as follow:

 library(psych) M <- data.frame(matrix(ncol=3,nrow=ncol(p))) M[,1] <- as.character() G <- colnames(p) for(rs in 1:ncol(p){ M[rs,1] <- G[rs] cor <- corr.test(as.data.frame(p[,rs]),as.data.frame(e[,rs]), method="spearman",adjust="none") M[rs,2] <- cor$r M[rs,3] <- cor$p } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.