在R中绘制相关矩阵

plotting correlation matrix in 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... 类似于下图,我在网上找到的其他案例:

我该如何解决这个问题?

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