【问题标题】:Correlation coefficient相关系数
【发布时间】:2018-06-15 13:37:50
【问题描述】:

首先,如果这个问题太简单了,我很抱歉。我试图从我的数据框的三行计算相关系数:

df=structure(list(Id = 1:3, V1 = c(27L, 40L, 29L), V2 = c(70L, 
101L, 48L), V3 = c(68L, 84L, 55L), V4 = c(48L, 80L, 39L), V5 = c(58L, 
73L, 38L), V6 = c(80L, 103L, 46L), V7 = c(99L, 115L, 52L), V8 = c(46L, 
82L, 58L), V9 = c(26L, 38L, 33L), V10 = c(13L, 17L, 13L)), .Names = c("Id", 
"V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10"), row.names = c(2L, 
5L, 8L), class = "data.frame")

我正在做的是将这些行转换为向量数字

df=df[-1]

g=as.numeric(df[1,])
h=as.numeric(df[2,])
i=as.numeric(df[3,])

并运行相关性 2 per 2:

> cor(g,h)
[1] 0.9530113
> cor(g,i)
[1] 0.7557693
> cor(h,i)
[1] 0.8519315

我对此进行了搜索,但似乎没有这样的功能cor(g,h,i),而是我无法运行cor(df),但它会给我所有V1:V10之间的相关性。

总之,有没有函数可以让我执行cor(g,h,i)并返回给我三个相关系数(0.9530113 , 0.7557693 , 0.8519315)或者比我的更优化的方法。

【问题讨论】:

  • cor(t(df[-1])) 会给你相关矩阵。您可以使用upper.trilower.tri 来获得相关性,例如cor_mat <- cor(t(df[-1])); cor_mat[upper.tri(cor_mat)]
  • 只是添加到@JasonWang 的答案。 d = cor(t(df[,-1])); d[lower.tri(d)] 会给你一个向量的结果。
  • > 看到这个解决方案Correlation coefficient using corrlY

标签: r


【解决方案1】:

如果你想要一个函数:

corr <-function(data,g,h,i) {
 m <- cor(data[,c(g,h,i)])
 m[upper.tri(m)]
}

【讨论】:

    【解决方案2】:
    # Get the correlation matrix by row
    cor(t(df[-1]))
    #           2         5         8
    # 2 1.0000000 0.9530113 0.7557693
    # 5 0.9530113 1.0000000 0.8519315
    # 8 0.7557693 0.8519315 1.0000000
    
    # Retrieve the correlation as vector
    cor_mat <- cor(t(df[-1]))
    cor_mat[upper.tri(cor_mat)]
    # [1] 0.9530113 0.7557693 0.8519315
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2011-09-11
      • 2013-09-29
      • 2012-12-07
      • 2021-08-29
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多