Converting a data frame to a correlation matrix in R


This Content is from Stack Overflow. Question asked by fsneden

I have a data frame of correlation coefficients and p-values that I have created externally and want to read into R so I can use corrplot() and create a correlation matrix map. Corrplot requires the data to be in a correlation matrix, and even though I have read other questions, I am still confused how to create it. A preview of my data is as follows (with some random values):

var1, var2, cor, p 
lcca  lica  0.9  0.01
lcca  rcca  0.4  0.10
lcca  rica  0.4  0.24

where var1 and var2 are the two variables listed by name, cor is the coefficient and p is the significance value.

Currently, my incorrect code is as follows:

correlations <- read_csv("correlations.csv")
correlations <- rcorr(as.matrix(correlations))

If I understand correctly, I need to pivot_wider() before I can do the second line, but after I have it in a correlation matrix, it SHOULD run fine? I’ve managed it before on data that I created within R itself, with this code:

rawdata <- read_csv("rawdata.csv")   
dfcor <- cór(rawdata, method = "spearman", use = "complete.obs")
round(dfcor, 2)
dfcor <- rcorr(as.matrix(dfcor))

plot <- corrplot(dfcor$r, 
                 method = "circle", 
                 type = "upper", 
                 order = "original", 
                 p.mat = dfcor$P, 
                 sig.level = 0.05, 
                 insig = "blank", 
                 tl.col = "black", 
        = 90, 
                 diag = FALSE)

I feel I know what SHOULD be done, but I don’t necessarily know HOW to do it. Can anyone help?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?