【问题标题】:plotting correlation matrix in R在R中绘制相关矩阵
【发布时间】:2018-12-05 10:57:49
【问题描述】:

我对 R 了解不多。我有一个 .txt 文件,其中包含以前从长记录创建的相关矩阵。

文件中的文本类似于:

"15075060" "15085030" "15085040"
"15075060" 1 0.441716695007761 0.433807683928689
"15085030" 0.441716695007761 1 0.477591938543259
"15085040" 0.433807683928689 0.477591938543259 1

这是一个有代表性的例子,因为真正的矩阵要大得多。引号中的数字是相关的来源。 我使用 read.table 读取数据以创建数据框,然后将其转换为矩阵(称为 matto):

mattox =matrix(as.numeric(unlist(matto)),nrow=nrow(matto))

我得到一个这样的矩阵:

>mattox
          [,1]      [,2]      [,3]
[1,] 1.0000000 0.4417167 0.4338077
[2,] 0.4417167 1.0000000 0.4775919
[3,] 0.4338077 0.4775919 1.0000000

作为选项 2,如果我使用以下方法将其转换为矩阵:

as.matrix(sapply(matto, as.numeric))

然后我得到一个这样的矩阵:

> matto
         X.15075060 X.15085030 X.15085040
15075060  1.0000000  0.4417167  0.4338077
15085030  0.4417167  1.0000000  0.4775919
15085040  0.4338077  0.4775919  1.0000000

虽然我不知道为什么我在列标题的数字之前得到那些 X

当我尝试使用函数 corrplot 绘制这种相关性时,我为矩阵 mattox 获得了类似的结果:

corrplot(mattox, type="upper")

但问题是我在这里看不到列和行的头部名称(.txt 文件中引号中的数字)。对于另一个矩阵(matto),当我尝试使用 corrplot 时出现错误,错误显示:

Error in matrix(if (is.null(value)) logical() else value, nrow = nr, dimnames = list(rn,  : 
  length of 'dimnames' [2] not equal to array extent

我想获得一个与我获得的图形一样的图形,但使用列和行的名称而不是数字 1、2、3... 类似于下一张图,我在网上为其他案例找到的:

我该如何解决这个问题?

【问题讨论】:

    标签: r matrix plot correlation


    【解决方案1】:

    您可以跳过这些步骤,在阅读时将其强制转换为矩阵,并且应该已经是数字。由于names being duplicates,它会在名称前面加上x。不过你可以指定colnames

    df <- as.matrix(read.table("location/of/text.txt", row.names = 1))
    colnames(df) <- c("15075060", "15085030", "15085040")
    
    str(df) # check the structure, it's numeric so we're good
    num [1:3, 1:3] 1 0.442 0.434 0.442 1 ...
    - attr(*, "dimnames")=List of 2
     ..$ : chr [1:3] "15075060" "15085030" "15085040"
     ..$ : chr [1:3] "15075060" "15085030" "15085040"
    
    corrplot(df, type = "upper")
    

    【讨论】:

    • 谢谢@匿名懦夫!只有一个问题,因为我写的真实矩阵非常大,所以我自己创建向量 c() 不是一种选择。读取.txt文件时如何自动创建?
    • 在这种情况下,只需添加一行:colnames(df) &lt;- row.names(df)
    猜你喜欢
    • 2012-07-19
    • 2015-10-20
    • 2023-02-21
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多