0
votes

I would like to create and plot a correlation matrix in R.

I have three vectors I create a dataFrame from. In a 2D-XY-Coordiante-System the vector "index" would be on the x-axis. And then I have two variables "var1" and "var2" (y-values) and every value with the same vector index belongs to the same index (x) value.

My tries to plot a correlation matrix faliled as I am not able to prepare my data in a proper way.

How can I prepare my data for the follwing correlation plot?

                            var2
           900  800  700  600  500  400  300 200  
     900   
     800
     700
     600   filled with pairwise corrleation coefficients 
var1 500
     400
     300
     200

This is what I tried so far:

 var1 <- c(10,20,3,1,10,4,21,2)
 var2 <-  c(1,44,1,19,19,29,1,3)
 index <- c(200,300,400,500,600,700,800,900)

 df <- data.frame(id = index, y1 = var1, y2=var2)
 M <- cor(df)

 install.packages("corrplot")
 library('corrplot')
 corrplot(M, method = "circle")

Thank you very much!

1
Can you explain how your attempts failed? was there an error message?see24
With the example data the resulting maxtrix should be a 8 x 8 correlation matrix but it is only 3x3 as id, y1 and y2 are correlated.user2894356

1 Answers

1
votes

Hope this is what you are looking for.

library(tidyr)
library(corrplot)
(df_wide <- df %>% 
  gather(y, y_value, -id) %>% 
  spread(id, y_value))
#   y 200 300 400 500 600 700 800 900
#1 y1  10  20   3   1  10   4  21   2
#2 y2   1  44   1  19  19  29   1   3

Calculate the correlations and plot.

(M <- cor(df_wide[-1]))
#    200 300 400 500 600 700 800 900
#200   1  -1   1  -1  -1  -1   1  -1
#300  -1   1  -1   1   1   1  -1   1
#400   1  -1   1  -1  -1  -1   1  -1
#500  -1   1  -1   1   1   1  -1   1
#600  -1   1  -1   1   1   1  -1   1
#700  -1   1  -1   1   1   1  -1   1
#800   1  -1   1  -1  -1  -1   1  -1
#900  -1   1  -1   1   1   1  -1   1

corrplot(M, method = "circle")

enter image description here