Easily input a correlation matrix in R

2020-07-11 06:14发布

I have a R script I'm running now that is currently using 3 correlated variables. I'd like to add a 4th, and am wondering if there's a simple way to input matrix data, particularly for correlation matrices---some Matlab-like technique to enter a correlation matrix, 3x3 or 4x4, in R without the linear to matrix reshape I've been using.

In Matlab, you can use the semicolon as an end-row delimiter, so it's easy to keep track of where the cross correlations are.

In R, where I first create

corr <- c(1, 0.1, 0.5,
0.1, 1, 0.9,
0.5, 0.9, 1)
cormat <- matrix(corr, ncol=3)

Versus

cormat = [1 0.1 0.5; 
0.1 1 0.9; 
0.5 0.9 1]

It just feels clunkier, which makes me suspect there's a smarter way I haven't looked up yet. Thoughts?

标签: r correlation
6条回答
Summer. ? 凉城
2楼-- · 2020-07-11 06:41

If you want to input a symmetric matrix, you can use the xpnd() function in the MCMCpack library.

xpnd() takes a vector which corresponds to the upper-triangle of the matrix (thus you only have to enter each value once). For instance, if you want to input:

$\left(\begin{array}{c c c} 1 & 0.1 & 0.5 \\ 0.1 & 1 & 0.9 \\ 0.5 & 0.9 & 1 \end{array}\right)$

You would use

library(MCMCpack)
xpnd(c(1, 0.1, 0.5, 1, 0.9, 1), 3)

where 3 refers to the number of rows in the matrix.

Help page for xpnd.

查看更多
狗以群分
3楼-- · 2020-07-11 06:44

As you are working with correlation matrices, you are probably not interested in entering the diagonal, and both the upper and lower parts. You can manipulate/extract those three parts separately using diag(), upper.tri() and lower.tri().

> M <- diag(3) # create 3x3 matrix, diagonal defaults to 1's
> M[lower.tri(M, diag=F)] <- c(0.1, 0.5, 0.9) # read in lower part
> M # lower matrix containing all information
      [,1] [,2] [,3]
 [1,]  1.0  0.0    0
 [2,]  0.1  1.0    0
 [3,]  0.5  0.9    1

If you want the full matrix:

> M[upper.tri(M, diag=F)] <- M[lower.tri(M)] # fill upper part
> M # full matrix
      [,1] [,2] [,3]
 [1,]  1.0  0.1  0.5
 [2,]  0.1  1.0  0.9
 [3,]  0.5  0.9  1.0
查看更多
可以哭但决不认输i
4楼-- · 2020-07-11 06:46

Here is another way:

CorrMat <- matrix(scan(),3,3,byrow=TRUE)
1 0.1 0.5
0.1 1 0.9
0.5 0.9 1

Trailing white line is important.

查看更多
ら.Afraid
5楼-- · 2020-07-11 06:49
rbind(c(1, 0.1, 0.5),
      c(0.1, 1, 0.9),
      c(0.5, 0.9, 1))
查看更多
相关推荐>>
6楼-- · 2020-07-11 07:02

For the existing solutions. That may only work for 3*3 matrix. I tried this one.

a<-diag(3)
m<-diag(3)
m[lower.tri(m,diag=F)]<-c(0.1, 0.5, 0.9)
m<-m+t(m)-a
查看更多
小情绪 Triste *
7楼-- · 2020-07-11 07:04

Welcome to the site! :) you should be able to do it in one step:

MyMatrix = matrix( 
    c(1, 0.1, 0.5, 
      0.1, 1, 0.9,
      0.5, 0.9, 1), 
    nrow=3, 
    ncol=3) 
查看更多
登录 后发表回答