gpt4 book ai didi

r - 在 r 的聚类分析中找不到相关性

转载 作者:行者123 更新时间:2023-12-05 05:38:08 25 4
gpt4 key购买 nike

这是我正在处理的数据集,来自链接:https://worldhappiness.report/ed/2022/文件名:Data_for_Figure_2.1

我试图找出变量在相关图中的相关性,代码如下所示

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

我不明白这是什么意思,为什么找不到“相关性”?我的代码中的“as.is”在哪里?
有人可以帮忙吗?

最佳答案

当我在包 reshape 中使用 melt() 时,我设法重现了您的错误。几年前,Just FYI reshape 已被 tidyverse 软件包套件所取代,我强烈建议切换到 ( https://www.tidyverse.org/packages/ )。在 tidyverse 中,您将使用函数 pivot_longer() 而不是 melt()

如果你单独运行 melt(corr, varnames = c("x", "y"), value.name = "correlation"),你会发现没有结果名为 correlation 的列,这就是 ggplot 无法找到它的原因。 value.name 参数来自 reshape2,它取代了您使用的包。因此,您可以手动重命名第 3 列,切换到 reshape2 中的 melt 或切换到我推荐的 tidyverse。这是使用 tidyverse 中的 pivot_longer() 的相同逻辑:

library(tidyverse)
corr <- cor(happy22[, 3:8], method = "pearson",
use = "complete.obs")
corr %>%
as.data.frame() %>%
rownames_to_column('x') %>%
pivot_longer(-x,
names_to = 'y',
values_to = 'correlation') %>%
ggplot(.,
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)

corr ggplot

关于r - 在 r 的聚类分析中找不到相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73008138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com