I have this code to generate symmetric matrices for testing how the design of the canonical correlation analysis I am performing works out. This is a extension of this solution
Each row of the matrix represent a dataset (it is symmetric), and if the value is 0 it means no interaction between the datasets, if it is higher that there is an interaction. The end goal of this code is just to make a grid search of the design that explains better the data I have.
However as I need to come up with different designs adding more datasets or less I would like to know how to improve this into a function that would be more general, specially the nested for loops part (If I test it with 5 datasets I add more for
loops and then more unlist
at the end).
Initial matrix (I usually work with 4 datasets):
C <- matrix(0,ncol = 4, nrow = 4)
Weights for the interactions of each dataset (4 to avoid to many combinations):
nweight <- 4
weight <- seq(from = 0, to = 1, length.out = nweight)
Initiate the list that will contain the matrices
C_list <- vector("list", nweight)
cweight <- as.character(weight)
names(C_list) <- cweight
Loop for each position I want to change to obtain all the combinations of weights I want to test.
for(i1 in cweight) {
C_list[[as.character(i1)]] <- vector("list", nweight)
names(C_list[[(i1)]]) <- cweight
for (i2 in cweight) {
C_list[[(i1)]][[(i2)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]]) <- cweight
for (i3 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]]) <- cweight
for(i4 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]]) <- cweight
for (i5 in cweight) {
C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]] <- vector("list", nweight)
names(C_list[[(i1)]][[(i2)]][[(i3)]][[(i4)]][[(i5)]]) <- cweight
for (i6 in cweight) {
C[1, 2] <- as.numeric(i1)
C[2, 1] <- as.numeric(i2)
C[1, 3] <- as.numeric(i2)
C[3, 1] <- as.numeric(i2)
C[1, 4] <- as.numeric(i3)
C[4, 1] <- as.numeric(i3)
C[2, 3] <- as.numeric(i4)
C[3, 2] <- as.numeric(i4)
C[2, 4] <- as.numeric(i5)
C[4, 2] <- as.numeric(i5)
C[4, 3] <- as.numeric(i6)
C[3, 4] <- as.numeric(i6)
C_list[[i1]][[i2]][[i3]][[i4]][[i5]][[i6]] <- C
}
}
}
}
}
}
Unlist the list of list of list of ... nested matrices to end up with a long list of matrices with the weights for each dataset
C_list2 <- unlist(unlist(unlist(unlist(unlist(C_list, FALSE, FALSE),
FALSE, FALSE), FALSE, FALSE),
FALSE, FALSE), FALSE, FALSE)