2017-05-03 56 views
3

我有這樣雙環填寫相關矩陣

​​

的數據集,我想獲得一個表

c d 
a 0.5 0.1 
b 0.8 0.3 

其中cols和rows是變量和細胞 - 間相關係數變量。

我做如下

for(j in df[, 1:2])   { 
for(i in df[, 3:4]) { 

    k=abs(cor.test(j, i, method = c("spearman"))$estimate) 
    cat(k, '\n') 
    y <- rbind(y, k) 
}} 
y 

,並得到

rho 
k 0.175757576 
k 0.006060606 
k 0.151515152 
k 0.054545455 

我用這篇文章Using double loop to fill a matrix in R

mat<-matrix(list(c(NA,NA)), nrow=2, ncol=2) 
for(j in df[, 1:2])   { 
    for(i in df[, 3:4]) { 

    mat[i,j][[1]]=abs(cor.test(j, i, method = c("spearman"))$estimate) 

    }} 
mat 

,我也得到

 [,1]  [,2]  
[1,] Logical,2 Logical,2 
[2,] Logical,2 Logical,2 

如何填表?或者我可以填充它沒有循環?

  • 在真實數據集諸多變數和我上無法使用的工具,如ggpairs
+0

在這種情況下'肺心病(DF,方法= 「斯皮爾曼」)'我們得到矩陣4X4,但我想只是2X2 – Edward

+1

'肺心病(cbind(A,B),cbind(C,d))'? – jogo

+2

或@ d.b的另一個版本的回答'cor(df)[1:2,3:4]' – G5W

回答

2

我將計算爲df一個時間相關矩陣,然後子集什麼我需要的組合。這樣,您不必多次運行cor

m = cor(df, method = "spearman") 
m[row.names(m) %in% c("a","b"), colnames(m) %in% c("c","d")] 
#   c   d 
#a 0.05454545 -0.40606061 
#b 0.75757576 0.05454545 
1

功能cor()能做到這一點:

set.seed(1) 
a = abs(rnorm(10, mean = 0, sd= 1)) 
b = abs(rnorm(10, mean = 0, sd= 1)) 
c = abs(rnorm(10, mean = 0, sd= 1)) 
d = abs(rnorm(10, mean = 0, sd= 1)) 
#### df = as.data.frame(cbind(a, b, c, d)) # not used 
cor(cbind(a,b), cbind(c,d)) 
# > cor(cbind(a,b), cbind(c,d)) 
#   c   d 
# a 0.5516642 -0.3918783 
# b 0.8200195 0.1474773 

而且你可以爲你想要的結果做abs()

abs(cor(cbind(a,b), cbind(c,d))) 
# > abs(cor(cbind(a,b), cbind(c,d))) 
# c   d 
# a 0.5516642 0.3918783 
# b 0.8200195 0.1474773 

斯皮爾曼:

abs(cor(cbind(a,b), cbind(c,d), method = "spearman")) 
# > abs(cor(cbind(a,b), cbind(c,d), method = "spearman")) 
# c   d 
# a 0.05454545 0.40606061 
# b 0.75757576 0.05454545 

如果你想使用你的數據框,你可以這樣做:

df = as.data.frame(cbind(a, b, c, d)) 
rm(a,b,c,d) ### to be sure that a, ..., d are from the dataframe. 
with(df, abs(cor(cbind(a,b), cbind(c,d), method = "spearman"))) 

abs(cor(df[,c("a", "b")], df[,c("c","d")], method = "spearman"))