Skip to content
Prev 396613 / 398502 Next

please help generate a square correlation matrix

?s 17:39 de 25/07/2024, Yuan Chun Ding via R-help escreveu:
Hello,

You are complicating the code, there's no need for as.symbol/eval, the 
column numbers do exactly the same.

# create the two results matrices beforehand
r <- P <- matrix(NA, nrow = 4L, ncol = 4L, dimnames = list(names(dat), 
names(dat)))

for(i in 1:4) {
   x <- dat[[i]]
   for(j in (1:4)) {
     if(i == j) {
       # there's nothing to test, assign correlation 1
       r[i, j] <- 1
     } else {
       tmp <- cor.test(x, dat[[j]])
       r[i, j] <- tmp$estimate
       P[i, j] <- tmp$p.value
     }
   }
}

# these two results are equal up to floating-point precision
dat.rcorr$r
#>           g1        g2        g3        g4
#> g1 1.0000000 0.1000000 0.3162278 0.1581139
#> g2 0.1000000 1.0000000 0.3162278 0.6324555
#> g3 0.3162278 0.3162278 1.0000000 0.0000000
#> g4 0.1581139 0.6324555 0.0000000 1.0000000
r
#>           g1        g2           g3           g4
#> g1 1.0000000 0.1000000 3.162278e-01 1.581139e-01
#> g2 0.1000000 1.0000000 3.162278e-01 6.324555e-01
#> g3 0.3162278 0.3162278 1.000000e+00 1.355253e-20
#> g4 0.1581139 0.6324555 1.355253e-20 1.000000e+00

# these two results are equal up to floating-point precision
dat.rcorr$P
#>           g1         g2        g3         g4
#> g1        NA 0.79797170 0.4070838 0.68452834
#> g2 0.7979717         NA 0.4070838 0.06758329
#> g3 0.4070838 0.40708382        NA 1.00000000
#> g4 0.6845283 0.06758329 1.0000000         NA
P
#>           g1         g2        g3         g4
#> g1        NA 0.79797170 0.4070838 0.68452834
#> g2 0.7979717         NA 0.4070838 0.06758329
#> g3 0.4070838 0.40708382        NA 1.00000000
#> g4 0.6845283 0.06758329 1.0000000         NA


You can put these two results in a list, like Hmisc::rcorr does.

lst_rcorr <- list(r = r, P = P)


Hope this helps,

Rui Barradas