簡體   English   中英

相關系數

[英]Correlation coefficient

首先,對不起,這個問題如此基本。 我正在嘗試僅從數據幀的三行計算相關系數:

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.9530113 , 0.7557693 , 0.8519315)

# 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

如果需要功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM