1

I want to calculate correlation matrix P which each P[i,j] is correlation coefficient of row i and col j in matrix Data. for example

  Data <- matrix(rnorm(500),50,10)
  P <- matrix(0,50,50)
  for (i in 1:50) 
     for(j in 1:50)
        P[i,j] <- cor(Data[i,],Data[j,])

But how can I use apply or something like this command to calculate such correlations.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
morteza
  • 77
  • 1
  • 7
  • As stated the request is impossible to satisfy since your rows and columns are not of equal length. – IRTFM Oct 10 '12 at 18:06

1 Answers1

6

You can just use cor() on a data frame or matrix to obtain a correlation matrix of correlations between all pairs of columns:

cor(t(Data))

From your question and code it is not clear if you want correlations for all pairs of rows or correlations between rows and columns, but since the matrix is not square I assumed the first.

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • Oh, my god, it have a very simple solution Thanks Sacha. but I have a question from you. how can I use two variate function for all pairs of rows of a matrix by apply? – morteza Oct 10 '12 at 14:33
  • I had a similar question a while back (http://stackoverflow.com/q/5233308/567015). Easiest way is to use `outer`, e.g. `outer(1:nrow(Data),1:nrow(Data),function(i,j)SOMEFUNCTION(Data[i,j],Data[j,]))`. However this is slow and very often you can find that there is a much easier way to do it. – Sacha Epskamp Oct 10 '12 at 14:40
  • Ok, I know that. But I think for having lower system time, there is another way for computing such as apply. I find it and send for you too. Re thanks Sacha – morteza Oct 10 '12 at 14:48
  • 2
    `apply` doesn't really lower computing time. Basically it is just a another way to write a loop. Same as with `outer` really. – Sacha Epskamp Oct 10 '12 at 14:51