# [R] matrix merging question

arun smartpink111 at yahoo.com
Tue Feb 25 22:28:39 CET 2014

```Hi,
I am not sure about your final result.  In your initial post, you mentioned "but with row names that need to be matched".  Anyway, this gives me symmetric matrix
##rownames are the same as colnames for each matrix, so:

uNrownames <- unique(as.vector(sapply(lst2,rownames)))
res <- matrix(0,nrow=length(uNrownames), ncol=length(uNrownames), dimnames=list(uNrownames,uNrownames))
for(i in seq_along(lst2)){
res[rownames(lst2[[i]]),rownames(lst2[[i]])] <- res[rownames(lst2[[i]]),rownames(lst2[[i]])] + lst2[[i]]
res
}

isSymmetric(res)
# TRUE
dim(res)
# 90 90

A.K.

On Tuesday, February 25, 2014 4:17 PM, Elio Shijaku <selius at gmail.com> wrote:

Hi Arun,

Yes, I figured that, thanks a lot for your help.

Howver, when I test res1 for symmetricity I get:

> isSymmetric(unname(res1))  FALSE

I need the final matrix to be symmetric.

Any idea?

E.

On Tue, Feb 25, 2014 at 10:14 PM, arun <smartpink111 at yahoo.com> wrote:

Hi,
>Sorry, a typo:
>
>
> res1[rownames(mat1),] <- res[rownames(mat1),] + mat1
>                          ###should be:
>
>res1[rownames(mat1),] <- res1[rownames(mat1),] + mat1
>
>A.K.
>
>
>On Tuesday, February 25, 2014 4:03 PM, arun <smartpink111 at yahoo.com> wrote:
>HI Elio,
>Not sure whether this helps:
>length(list.files(pattern=".txt"))
># 22
> sapply(lst1,dim)
> sapply(lst1,function(x) all(apply(rbind(colnames(x),rownames(x)),2,function(y) y==y)))
> # TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
># TRUE TRUE TRUE TRUE TRUE TRUE TRUE
>lst2 <- lapply(lst1,as.matrix)
>uNrownames <- unique(as.vector(sapply(lst2,rownames)))
>res1 <- matrix(0,nrow=length(uNrownames), ncol=ncol(lst2[]), dimnames=list(uNrownames,NULL))
>
>for(i in seq_along(lst2)){
>  mat1 <- lst2[[i]]
> res1[rownames(mat1),] <- res[rownames(mat1),] + mat1
> res1
> }
>
> dim(res1)
># 90 90
>
>
>
>A.K.
>
>
>
>
>
>
>
>
>On Tuesday, February 25, 2014 2:52 PM, Elio Shijaku <selius at gmail.com> wrote:
>
>Hi Arun,
>
>I wanted to ask you again on the issue of merging several matrices. I tried to look through R-related pages on how to merge several symmetric matrices of same dimension (90x90) but with row names that need to be matched, but I didn't find any solution. What I found concerned the merging of two matrices which are not symmetric and that is not my case.
>
>Can you help me with any code?
>
>Attached are the files (in tab delimited text and/ Excel) that need to be merged.
>
>What I want is a 90x90 final matrix that is the sum (aggregate) of all 22 matrices and that matches each variable.
>
>I would appreciate your help if possible.
>
>Best,
>
>Elio
>

```