correlation not found in Cluster Analysis in r

Viewed 46

here is the dataset I am working on, from the link: https://worldhappiness.report/ed/2022/ file name: Data_for_Figure_2.1

I am trying to find how the variables correlate in a correlation map, the code was written as below

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)

the error shows:

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

I cant figure out what this means, why 'correlation' not found? where is 'as.is' in my code?
Could anyone please help?

1 Answers

I managed to replicate your error when I used melt() in the package reshape. Just FYI reshape has been superseded by the suite of tidyverse packages a few years ago which I highly recommend switching to (https://www.tidyverse.org/packages/). In the tidyverse you would use the function pivot_longer() instead of melt().

If you run melt(corr, varnames = c("x", "y"), value.name = "correlation") on its own, you'll notice there is no resulting column called correlation and that is why ggplot isn't able to find it. The value.name argument is from reshape2, the package that superseded the package you used. So, you could either manually rename your 3rd column, switch to melt in reshape2 or switch to the tidyverse, which I would recommend. Here is the same logic using pivot_longer() from the tidyverse:

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

Related