Blind0ne
Blind0ne

Reputation: 1037

R sum matrices with different dimensions in a list and return a matrix

This could be easy but I can't seem to figure it out. I have a list which consists of matrices:

randomString <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

mat_names <- randomString(10)

mat1 <- matrix(sample(1:100, 10), nrow = 1, ncol = 10)
colnames(mat1) <- mat_names[1:10]

mat2 <- matrix(sample(1:100, 7), nrow = 1, ncol = 7)
colnames(mat2) <- mat_names[1:7]

mat3 <- matrix(sample(1:100, 3), nrow = 1, ncol = 3)
colnames(mat3) <- mat_names[1:3]

matlist <- list(
  "mat1"=mat1,
  "mat2"=mat2,
  "mat3"=mat3
)
print(matlist)

Output:

$mat1
     YDBTT5207K DJTTX5635J XADWJ8211U SPPLC7331C DKSHW5279Z VSTXA0199O RELXP9721L SQQFH3616Q JFZFB3125N NWKCT9607I
[1,]         93         72         92         94         74         91         11         15         63         55

$mat2
     YDBTT5207K DJTTX5635J XADWJ8211U SPPLC7331C DKSHW5279Z VSTXA0199O RELXP9721L
[1,]         53         84         18         44         79         47        100

$mat3
     YDBTT5207K DJTTX5635J XADWJ8211U
[1,]         88         49         36

Now I want the sum of the columns based on their names, so a matrix like this:

     YDBTT5207K DJTTX5635J XADWJ8211U SPPLC7331C DKSHW5279Z VSTXA0199O RELXP9721L SQQFH3616Q JFZFB3125N NWKCT9607I
[1,]        234        205        146        138        153        138        111         15         63         55

How do I achieve it?

Upvotes: 0

Views: 67

Answers (2)

StupidWolf
StupidWolf

Reputation: 46908

Maybe like this:

allelem = Reduce(union,lapply(matlist,colnames))
unionMat = sapply(matlist,function(i)i[,match(allelem,colnames(i))])

           mat1 mat2 mat3
REBQG1509K   42    1   20
IHZKK6973T   24   10   89
XRSXL1970Q   30    9   88
UNGOW7172K   47    6   NA
RKJFP9148P   61   90   NA
YRVEA1199Q   74   11   NA
SBAUE6979O   23   20   NA
JRVKW2279O   84   NA   NA
SSTEO2503H    1   NA   NA
LEKKI1679Y   58   NA   NA

rowSums(unionMat,na.rm=TRUE)
REBQG1509K IHZKK6973T XRSXL1970Q UNGOW7172K RKJFP9148P YRVEA1199Q SBAUE6979O 
        63        123        127         53        151         85         43 
JRVKW2279O SSTEO2503H LEKKI1679Y 
        84          1         58

Upvotes: 1

Ben
Ben

Reputation: 30474

I suspect there are a number of different ways to approach this. One possible method is to create a data frame from your list that will combine values from like names. Missing elements for a given name will be NA. Then, calculate sums with colSums and show result as transposed matrix.

library(dplyr)

bind_rows(lapply(matlist, as.data.frame)) %>%
  colSums(na.rm = TRUE) %>%
  as.matrix() %>%
  t()

Upvotes: 1

Related Questions