【问题标题】:Double loop to fill a correlation matrix双循环填充相关矩阵
【发布时间】:2017-10-01 16:46:08
【问题描述】:

我有一个这样的数据集

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))

我想要一张桌子

   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这样的工具

【问题讨论】:

  • 在这种情况下cor(df, method = "spearman") 我们得到矩阵 4X4 但我只想要 2X2
  • cor(cbind(a,b), cbind(c,d)) ?
  • 或@d.b 的另一个版本的答案cor(df)[1:2, 3:4]

标签: r loops matrix


【解决方案1】:

我会计算一次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

【讨论】:

    【解决方案2】:

    函数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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 2013-01-19
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多