r - 在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 ......类似于下一个图形,我在网上为其他情况找到了该图形:
我怎样才能解决这个问题?
解决方案
您可以跳过这些步骤,并在阅读时将其强制转换为矩阵,并且应该已经是数字。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")
推荐阅读
- python - 如何优化在 Python 中搜索大文件
- c# - 我们可以在visualstudio 2019 中使用visualstudio 2010 源代码吗?
- reactjs - 如何在反应中显示上传到cloudinary的图像“加载资源失败:服务器响应状态为404()”
- java - VSCode java如何设置编译后的.class文件的路径?
- amazon-web-services - AWS Control Tower 创建的 aws 多账户环境中的 Terraform
- reactjs - MaterialTable 中的值未更新
- c++ - 聚合 - 如何优雅地释放为对象分配的内存?- 里面的细节
- css - WP&woocommerce CSS img 大小在页脚中发生冲突
- sql - 尝试将 SQL getdate 转换为没有中间字符的 varchar
- python - 在迭代多个文件时创建与正则表达式模式匹配的字符串列表