Converting a data frame to a correlation matrix in R

Viewed 27

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", 
                 tl.srt = 90, 
                 diag = FALSE)

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

0 Answers
Related