首页 > 解决方案 > 在R中绘制相关矩阵

问题描述

我对 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 ......类似于下一个图形,我在网上为其他情况找到了该图形:

在此处输入图像描述

我怎样才能解决这个问题?

标签: rmatrixplotcorrelation

解决方案


您可以跳过这些步骤,并在阅读时将其强制转换为矩阵,并且应该已经是数字。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")

推荐阅读