从R中的相关向量创建相关矩阵 [英] Create a Correlation Matrix From a Correlation Vector in R

查看:189
本文介绍了从R中的相关向量创建相关矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在给定相关矢量的情况下创建一个相关矩阵,它是相关矩阵的上(或下)三角矩阵.

I want to create a correlation matrix given the correlation vector, which is the upper (or lower) triangular matrix of the correlation matrix.

目标是转换此向量

在对角线上有1s的相关矩阵.

to this correlation matrix with 1s on the diagonal.

您是否知道有没有一种方法可以在对角线上方的三角形处创建矩阵并将对角线设置为1?

Do you know if there is a method creating a matrix given the triangular above the diagonal and to set the diagonal to 1?

推荐答案

我不知道是否有自动方法,但是请扩展我的评论:

I don't know if there is an automatic way to do this, but expanding on my comment:

myvec <- c(-.55, -.48, .66, .47, -.38, -.46)
mempty <- matrix(0, nrow = 4, ncol = 4)
mindex <- matrix(1:16, nrow = 4, ncol = 4)
mempty[mindex[upper.tri(mindex)]] <- myvec
mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))]
diag(mempty) <- 1
mempty
#       [,1]  [,2]  [,3]  [,4]
# [1,]  1.00 -0.55 -0.48  0.47
# [2,] -0.55  1.00  0.66 -0.38
# [3,] -0.48  0.66  1.00 -0.46
# [4,]  0.47 -0.38 -0.46  1.00


这是一个快速被黑客入侵的功能.我希望我所有的数学步骤都是正确的!


Here's a quickly hacked together function. I hope all my mathematics steps are correct!

vec2symmat <- function(invec, diag = 1, byrow = TRUE) {
  Nrow <- ceiling(sqrt(2*length(invec)))

  if (!sqrt(length(invec)*2 + Nrow) %% 1 == 0) {
    stop("invec is wrong length to create a square symmetrical matrix")
  }

  mempty <- matrix(0, nrow = Nrow, ncol = Nrow)
  mindex <- matrix(sequence(Nrow^2), nrow = Nrow, ncol = Nrow, byrow = byrow)
  if (isTRUE(byrow)) {
    mempty[mindex[lower.tri(mindex)]] <- invec
    mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))]
  } else {
    mempty[mindex[upper.tri(mindex)]] <- invec
    mempty[lower.tri(mempty)] <- t(mempty)[lower.tri(t(mempty))]
  }

  diag(mempty) <- diag
  mempty
}

此处对角线的值不同.

Here it is with a different value for the diagonal.

vec2symmat(1:3, diag = NA)
#      [,1] [,2] [,3]
# [1,]   NA    1    2
# [2,]    1   NA    3
# [3,]    2    3   NA

如果您尝试提供无法创建方矩阵的数据,则会出现错误消息.

Here's an error message if you try to provide data that can't create a square matrix.

vec2symmat(1:4)
# Error in vec2symmat(1:4) : 
#   invec is wrong length to create a square symmetrical matrix

并且,使用默认设置.

vec2symmat(1:10)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    2    3    4
# [2,]    1    1    5    6    7
# [3,]    2    5    1    8    9
# [4,]    3    6    8    1   10
# [5,]    4    7    9   10    1

这篇关于从R中的相关向量创建相关矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆