【发布时间】: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.tri或lower.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