【问题标题】:Prepare data for correlation matrix为相关矩阵准备数据
【发布时间】:2018-08-02 19:39:30
【问题描述】:

我想在 R 中创建并绘制一个相关矩阵。

我有三个向量,我从中创建了一个数据帧。 在 2D-XY-Coordiante-System 中,矢量“索引”将位于 x 轴上。 然后我有两个变量“var1”和“var2”(y 值),每个具有相同向量索引的值都属于相同的索引 (x) 值。

我尝试绘制相关矩阵失败了,因为我无法以正确的方式准备我的数据。

如何为以下相关图准备数据?

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

这是我迄今为止尝试过的:

 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")

非常感谢!

【问题讨论】:

  • 您能解释一下您的尝试是如何失败的吗?有错误信息吗?
  • 对于示例数据,生成的 maxtrix 应该是一个 8 x 8 的相关矩阵,但它只有 3x3 的 id,y1 和 y2 是相关的。

标签: r


【解决方案1】:

希望这是您正在寻找的。​​p>

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

计算相关性并绘图。

(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")

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2018-10-19
    • 2012-11-04
    相关资源
    最近更新 更多