首先,如果这个问题非常基本,我很抱歉。我只想从我的数据帧的三行计算相关系数:
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运行相关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)
或比我更优化的方法返回给我。
答案 0 :(得分: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
答案 1 :(得分:0)
如果你想要一个功能:
corr <-function(data,g,h,i) {
m <- cor(data[,c(g,h,i)])
m[upper.tri(m)]
}