[英]Generate covariance matrix from correlation matrix
I have a correlation matrix:我有一个相关矩阵:
a <- matrix(c(1, .8, .8, .8, 1, .8, .8, .8, 1), 3)
## [,1] [,2] [,3]
## [1,] 1.0 0.8 0.8
## [2,] 0.8 1.0 0.8
## [3,] 0.8 0.8 1.0
I would now like to create a covariance matrix from the correlation matrix.我现在想从相关矩阵创建一个协方差矩阵。 How can this be done in R?这如何在 R 中完成?
I tried:我试过了:
e1.sd <- 3
e2.sd <- 10
e3.sd <- 3
e.cov <- a * as.matrix(c, e1.sd, e2.sd, e3.sd) %*% t(as.matrix(c(e1.sd, e2.sd, e3.sd)))
But I get the error:但我收到错误:
Error in a * as.matrix(c, e1.sd, e2.sd, e3.sd) %*% t(as.matrix(c(e1.sd, :
non-conformable arrays
What am I doing wrong?我究竟做错了什么?
If you know the standard deviations of your individual variables, you can:如果您知道各个变量的标准差,您可以:
stdevs <- c(e1.sd, e2.sd, e3.sd)
#stdevs is the vector that contains the standard deviations of your variables
b <- stdevs %*% t(stdevs)
# b is an n*n matrix whose generic term is stdev[i]*stdev[j] (n is your number of variables)
a_covariance <- b * a #your covariance matrix
On the other hand, if you don't know the standard deviations, it's impossible.另一方面,如果你不知道标准差,那是不可能的。
require(MBESS)
a <- matrix(c(1,.8,.8,.8,1,.8,.8,.8,1),3)
> cor2cov(a,c(3,10,3))
[,1] [,2] [,3]
[1,] 9.0 24 7.2
[2,] 24.0 100 24.0
[3,] 7.2 24 9.0
Building on S4M's answer, in base R, I would write this function:基于 S4M 的答案,在基础 R 中,我将编写此函数:
cor2cov <- function(V, sd) {
V * tcrossprod(sd)
}
tcrossprod
will calculate the product of each combination of elements of the sd vector (equivalent to x %*% t(x)
), which we then (scalar) multiply by the variance-covariance matrix tcrossprod
将计算 sd 向量的每个元素组合的乘积(相当于x %*% t(x)
),然后我们(标量)乘以方差-协方差矩阵
Here's a quick check that the function is correct using the built in mtcars data set:下面是使用内置的 mtcars 数据集快速检查该函数是否正确:
all.equal(
cor2cov(cor(mtcars), sapply(mtcars, sd)),
cov(mtcars)
)
The answer marked as correct is wrong.标记为正确的答案是错误的。
The correct solution seems to be the one provided by MBESS package, so see the post from dayne.正确的解决方案似乎是 MBESS 包提供的解决方案,因此请参阅 dayne 的帖子。
> a
[,1] [,2] [,3]
[1,] 1.0 0.8 0.8
[2,] 0.8 1.0 0.8
[3,] 0.8 0.8 1.0
> b <- c(3,10,3)
> b %*% t(b)
[,1] [,2] [,3]
[1,] 9 30 9
[2,] 30 100 30
[3,] 9 30 9
> c <- b %*% t(b)
> c %*% a
[,1] [,2] [,3]
[1,] 40.2 44.4 40.2
[2,] 134.0 148.0 134.0
[3,] 40.2 44.4 40.2
> cor2cov(cor.mat=a, b )
[,1] [,2] [,3]
[1,] 9.0 24 7.2
[2,] 24.0 100 24.0
[3,] 7.2 24 9.0
> a %*% c
[,1] [,2] [,3]
[1,] 40.2 134 40.2
[2,] 44.4 148 44.4
[3,] 40.2 134 40.2
>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.