R语言聚类分析相关性报错求助:correlation对象未找到
问题:相关性热力图代码报错'correlation'未找到及'as.is'警告
我使用《世界幸福报告2022》中的Data_for_Figure_2.1数据集,编写R代码绘制变量相关性热力图,代码如下:
corr <- cor(happy22[, 3:8], method = "pearson") ggplot(melt(corr, varnames = c("x", "y"), value.name = "correlation"), aes(x = x, y = y)) + geom_tile(aes(fill = correlation)) + scale_fill_gradient2( low = "green", mid = "yellow", high = "red", guide = guide_colorbar(ticks = FALSE, barheight = 5), limits = c(-1, 1) ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(title = "Heatmap of correlation matrix", x = NULL, y = NULL)
运行后出现错误及警告:
Error in FUN(X[[i]], ...) : object 'correlation' not found In addition: Warning messages: 1: In type.convert.default(X[[i]], ...) : 'as.is' should be specified by the caller; using TRUE 2: In type.convert.default(X[[i]], ...) : 'as.is' should be specified by the caller; using TRUE
疑问:为何提示'correlation'未找到?代码中并未出现'as.is',请求协助解决。
解决方案
错误原因解析
- 'correlation'未找到:你调用的
melt()来自基础R的reshape包,该版本的melt()不支持value.name参数——这个参数是reshape2或data.table包中melt()的特性。基础R的melt()会将值列默认命名为value,而非你指定的correlation,导致ggplot无法识别该变量。 - 'as.is'警告:同样是基础R
melt()的问题,它在转换数据时会自动调用type.convert(),但未明确指定as.is参数,因此触发警告。
修复后的代码
有两种可行方案:
方案1:使用reshape2包的melt函数
先安装并加载reshape2包,再执行代码:
# 首次运行需安装包 install.packages("reshape2") library(reshape2) corr <- cor(happy22[, 3:8], method = "pearson") ggplot(melt(corr, varnames = c("x", "y"), value.name = "correlation"), aes(x = x, y = y)) + geom_tile(aes(fill = correlation)) + scale_fill_gradient2( low = "green", mid = "yellow", high = "red", guide = guide_colorbar(ticks = FALSE, barheight = 5), limits = c(-1, 1) ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(title = "Heatmap of correlation matrix", x = NULL, y = NULL)
方案2:使用基础R melt并手动重命名列
如果不想额外安装包,可保留基础R的melt(),手动修改值列名称:
corr <- cor(happy22[, 3:8], method = "pearson") # 转换格式后重命名第三列为correlation melted_corr <- melt(corr, varnames = c("x", "y")) colnames(melted_corr)[3] <- "correlation" ggplot(melted_corr, aes(x = x, y = y)) + geom_tile(aes(fill = correlation)) + scale_fill_gradient2( low = "green", mid = "yellow", high = "red", guide = guide_colorbar(ticks = FALSE, barheight = 5), limits = c(-1, 1) ) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(title = "Heatmap of correlation matrix", x = NULL, y = NULL)
内容的提问来源于stack exchange,提问作者Tianna
相关产品推荐
相关产品推荐

