pophahpop
pophahpop

Reputation: 51

Adding combinations of rows to columns

I have 17 square matrices of order 430 and a large matrix of dimension 92235 x 34

  1. For each square matrix, I wish to add each row's value (from 1 to 430) to a column in the large matrix, taking only those values above the main diagonal. So [1,2][1,3][1,4]..[1,430][2,3][2,4]...[2,430]...[429,430] -- hence, the 92235 row length of the large matrix (A sample of Step 1 is shown here https://i.sstatic.net/VwYuG.jpg)

  2. The square matrix is transposed

  3. Step 1 is repeated but the row values are added to the next column in the large matrix

  4. Repeat Steps 1-3 16 more times until the large matrix is filled

How do I go about doing this?

TIA

EDIT FOR COMMENT

mat = matrix(1:25,5,5)
mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25

mat2 = cbind(mat[upper.tri(mat)])
mat2
      [,1]
[1,]    6
[2,]   11
[3,]   12
[4,]   16
[5,]   17
[6,]   18
[7,]   21
[8,]   22
[9,]   23
[10,]  24

This reads columns then rows. Instead, I would like to read rows then columns so that the result should be:

      [,1]
[1,]    6
[2,]   11
[3,]   16
[4,]   21
[5,]   12
[6,]   17
[7,]   22
[8,]   18
[9,]   23
[10,]  24

Upvotes: 0

Views: 79

Answers (1)

akrun
akrun

Reputation: 887981

If you have 17 square matrices ('m1', 'm2',...'m17'), keep them in a list and then use upper.tri to extract the elements above the diagonal and cbind with the elements from the transpose

 lst1 <- mget(paste0('m', 1:17))
 Out <- do.call(cbind,lapply(lst1, function(x) {x1 <- t(x)
                   cbind(x[upper.tri(x)], x1[upper.tri(x1)]) }))
 dim(Out)
#[1] 92235    34

Here I created the matrices in a list.

Update

Based on the row order of the data,

mat1 <- mat
mat1[lower.tri(mat1, diag=TRUE)] <- NA
as.vector(na.omit(unlist(tapply(mat1, row(mat1), FUN=I))))
#[1]  6 11 16 21 12 17 22 18 23 24

Or as @David Arenburg mentioned in the comments

temp <- t(mat)
temp[lower.tri(temp)]
#[1]  6 11 16 21 12 17 22 18 23 24

You can replace the steps as here in the lapply.

data

set.seed(24)
lst1 <- replicate(17, matrix(sample(1:200, 430*430, replace=TRUE), 
    430, 430), simplify=FALSE)

Upvotes: 3

Related Questions