简体   繁体   English

使用apply计算矩阵的相关矩阵

[英]calculate correlation matrix of a matrix with apply

I want to calculate correlation matrix P which each P[i,j] is correlation coefficient of row i and col j in matrix Data. 我想计算相关矩阵P,其中每个P [i,j]是矩阵Data中第i行和col j的相关系数。 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. 但是如何使用apply或类似此命令的内容来计算此类相关性。

You can just use cor() on a data frame or matrix to obtain a correlation matrix of correlations between all pairs of columns: 您可以仅在数据帧或矩阵上使用cor()来获取所有成对的列之间的相关性的相关性矩阵:

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. 从您的问题和代码来看,您是否想要所有行对或行与列之间的相关性尚不清楚,但是由于矩阵不是正方形,因此我假设是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM