[英]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: 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?我如何实现它?
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
.给定名称的缺失元素将是
NA
。 Then, calculate sums with colSums
and show result as transposed matrix.然后,使用
colSums
计算总和并将结果显示为转置矩阵。
library(dplyr)
bind_rows(lapply(matlist, as.data.frame)) %>%
colSums(na.rm = TRUE) %>%
as.matrix() %>%
t()
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.