0

I can see from the link below how to get a list of unique combinations and then how to combine this with self combinations

Non-redundant version of expand.grid

e.g.

 factors <- c("a", "b", "c")

 all.combos <- t(combn(factors,2))

 dup.combos <- cbind(factors,factors)

 all.combosnew <- rbind(all.combos,dup.combos)

     factors factors
 [1,] "a"     "b"    
 [2,] "a"     "c"    
 [3,] "b"     "c"    
 [4,] "a"     "a"    
 [5,] "b"     "b"    
 [6,] "c"     "c" 

However, I also need there to be duplicates of correlations, so there should be 9 combinations altogether

   "a"     "a"
   "a"     "b"    
   "a"     "c"
   "b"     "a"
   "b"     "b"    
   "b"     "c"    
   "c"     "a"    
   "c"     "b"    
   "c"     "c" 

This seems like it should be obvious, but I haven't found it yet. Any suggestions would be helpful.

Ultimately, I need to put this list of combinations into a foreach loop using cor.test and need all combinations to be listed, such that I can convert this into a matrix e.g 3x3.

       a       b      c
       1       x      x
       x       1      x
       x       x      1
  • 1
    You could use `expand.grid(factors, factors)`. – Martin Gal Apr 06 '23 at 22:05
  • 1
    https://stackoverflow.com/questions/22569176/how-to-generate-permutations-or-combinations-of-object-in-r/47983855#47983855 Maybe this "permutations / combinations" question with detailed overview of the options contains relevant starting points for you? – uke Apr 06 '23 at 22:27

1 Answers1

0

As Martin suggested, in this case, expand.grid is your friend. As you did not supply data, I've created some. The following may not be the most elegant solution, but it should give you an idea upon which you can expand.

# Using double letters so as to not overwrite "c"
factors <- c("aa", "bb", "cc")
# Create permutation list. Set stringsAsFactors to FALSE so we can use "get"
# later.
f2 <- expand.grid(factors, factors, stringsAsFactors = FALSE)
# Order on column 1
f2 <- f2[order(f2[, 1L]), ]
# Augment with correlation data.
set.seed(61L)
n <- 10000L
rho <- 0.7
aa <- rnorm(n, 0, 1)
bb <- rnorm(n, 0, 1)
cc <- rho * aa + sqrt(1 - rho ^ 2) * bb
# Always preallocate your return object if you can.
f2$cor <- 0
# Calculate correlations
for (i in seq_len(nrow(f2))) {
  f2$Cor[i] <- cor(get(f2$Var1[i]), get(f2$Var2[i]))
}

# Create Matrix
corM <- matrix(f2$Cor, ncol = 3L, dimnames = list(factors, factors))

corM
aa  1.00000000 -0.01064047 0.6978159
bb -0.01064047  1.00000000 0.7088116
cc  0.69781586  0.70881156 1.0000000
Avraham
  • 1,655
  • 19
  • 32