0

I have a 6x6 correlation matrix that I want to import:

 1.0000
 0.6008   1.0000
 0.4984   0.4749   1.0000
 0.1920   0.2196   0.2079   1.0000
 0.1959   0.1912   0.2010   0.4334   1.0000
 0.3466   0.2979   0.2445   0.3197   0.4207   1.0000

I've tried using scan() directly, but it won't input the matrix.

A <- matrix(scan("data.txt", n = 6*6), 6, 6, byrow = TRUE)

This didn't work because "data length [21] is not a sub-multiple or multiple of the number of rows [6]".

What other methods can be used to import an external, pre-existing correlation matrix?

smci
  • 32,567
  • 20
  • 113
  • 146
  • 4
    use `read.table()`if the data is a .txt file – etienne Oct 26 '15 at 21:00
  • Possible duplicate of [Import data into R with an unknown number of columns?](http://stackoverflow.com/questions/1874443/import-data-into-r-with-an-unknown-number-of-columns) – usεr11852 Oct 26 '15 at 21:07

1 Answers1

3

You could indeed use count.fields and read.table alone (see here), but I think the most appropriate solution is to make a symmetric matrix with xpnd from MCMCpack (no NA's in UD).

max_col <- max( count.fields("data.txt", sep = " ") ) # Insert \t if tab-separated 

library(MCMCpack)
A <- read.table("text.txt", sep=" ", fill=TRUE, col.names=1:max_col)
corr <- xpnd( A[lower.tri(A, diag=T)] , max_col)

Giving you

corr
#        [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
# [1,] 1.0000 0.6008 0.4984 0.1920 0.1959 0.3466
# [2,] 0.6008 1.0000 0.4749 0.2196 0.1912 0.2979
# [3,] 0.4984 0.4749 1.0000 0.2079 0.2010 0.2445
# [4,] 0.1920 0.2196 0.2079 1.0000 0.4334 0.3197
# [5,] 0.1959 0.1912 0.2010 0.4334 1.0000 0.4207
# [6,] 0.3466 0.2979 0.2445 0.3197 0.4207 1.0000
Community
  • 1
  • 1
harre
  • 7,081
  • 2
  • 16
  • 28