Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily input a correlation matrix in R

Tags:

r

correlation

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?

like image 357
Mittenchops Avatar asked Feb 16 '12 01:02

Mittenchops


2 Answers

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) 
like image 187
Michelle Avatar answered Oct 03 '22 18:10

Michelle


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.

like image 24
Sacha Epskamp Avatar answered Oct 03 '22 18:10

Sacha Epskamp