-3

I have a list that includes 20 matrices. I want to calculate Pearson's correlation betweeen all matrices. but I can not find any possible code or functions? Could you please give some tips for doing so.

something like:
a=matrix(1:8100, ncol = 90)
b=matrix(8100:16199, ncol = 90)
c=matrix(sample(16200:24299),ncol = 90)
z=list(a,b,c)

I find this: https://rdrr.io/cran/lineup/man/corbetw2mat.html and try it:

library(lineup)
corbetw2mat(z[a], z[b], what = "all")

I've got the following error:

Error in corbetw2mat(z[a], z[b], what = "all") : 
  (list) object cannot be coerced to type 'double'

I want a list like this for the result:

a & b 
correlations
a & c
correlations
b & c
correlations

Thanks

  • Welcome to stackoverflow! Your question is unclear, please read and edit your question according to [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) so that other users can help you. Also, add expected output. – pogibas Jul 13 '19 at 17:13
  • You have not really explained what it is that you expect as an answer. Best would be if you posted a code block that created a smaller number for which you could present a "correct" answer by hand. – IRTFM Jul 13 '19 at 17:22

1 Answers1

1

I will create a smaller data set to illustrate the solution below.
To get pairwise combinations the best option is to compute a matrix of combinations with combn and then loop through it, in this case a lapply loop.

set.seed(1234)    # Make the results reproducible

a <- matrix(1:9, ncol = 3)
b <- matrix(rnorm(9), ncol = 3)
c <- matrix(sample(1:9), ncol = 3)
sample_list <- list(a, b, c)

cmb <- combn(3, 2)
res <- lapply(seq.int(ncol(cmb)), function(i) {
  cor(sample_list[[ cmb[1, i] ]], sample_list[[ cmb[2, i] ]])
})

The results are in the list res.

Note that sample is a base r function, so I changed the name to sample_list.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thanks a lot. Sorry for asking this, I can't understand the cmb part; for my real data that contains 20 matrices, what combination should I use and more importantly why? – Bagher erfanian Jul 13 '19 at 18:52
  • @Baghererfanian From the help page `?combn`: *Generate all combinations of the elements of x taken m at a time.* So if you have 20 matrices, you get the pairs (1,2), then (1,3), etc until (1,20), then (2,3) etc. Replace the call in the answer by `cmb <- combn(20, 2)`. – Rui Barradas Jul 13 '19 at 18:57