Easy to enter correlation matrix in R

I have an R script I am running now, currently using 3 correlated variables. I would like to add a 4th, and I am wondering if there is an easy way to enter matrix data, in particular for correlation matrices --- some kind of Matlab-like method for inputting a 3x3 or 4x4 correlation matrix in R without a linear matrix, which I used.

In Matlab, you can use a semicolon as a delimiter for end lines, 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) 

Against

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

It just feels clunkier, which makes me suspect that the smarter way I haven't picked up yet. Thoughts?

+6
source share
6 answers

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 

An important important feature of the line.

+4
source

Welcome to the site! :) you have 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) 
+6
source

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

xpnd() takes a vector corresponding to the top triangle of the matrix (thus, you only need to enter each value once). For example, if you want to enter:

$ \ left (\ begin {array} {ccc} 1 and 0.1 and 0.5 \\ 0.1 and 1 and 0.9 \\ 0.5 and 0.9 and 1 \ End {array} \ right ) $

Would you use

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

where 3 is the number of rows in the matrix.

Help page for xpnd .

+4
source
 rbind(c(1, 0.1, 0.5), c(0.1, 1, 0.9), c(0.5, 0.9, 1)) 
+4
source

For existing solutions. This can only work for a 3 * 3 matrix. I tried this.

 a<-diag(3) m<-diag(3) m[lower.tri(m,diag=F)]<-c(0.1, 0.5, 0.9) m<-m+t(m)-a 
+3
source

When you work with correlation matrices, you are probably not interested in entering the diagonal, as well as the upper and lower parts. You can manipulate / extract these 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 to get 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 
+2
source

Source: https://habr.com/ru/post/908572/


All Articles