【问题标题】:How do you import an external correlation matrix from file in R?如何从 R 中的文件导入外部相关矩阵?
【发布时间】:2016-01-26 03:05:09
【问题描述】:

我有一个要导入的 6x6 相关矩阵:

 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

我尝试过直接使用scan(),但它不会输入矩阵。

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

这不起作用,因为“数据长度 [21] 不是行数 [6] 的约数或倍数”。

还有哪些其他方法可用于导入外部的、预先存在的相关矩阵?

【问题讨论】:

标签: r matrix correlation read.table data-import


【解决方案1】:

您确实可以单独使用count.fieldsread.table (see here),但我认为最合适的解决方案是使用来自MCMCpackxpnd 制作一个对称矩阵(没有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)

给你

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

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2014-07-26
    相关资源
    最近更新 更多