Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-具有不同列的矩阵的和列表_R_Matrix_Sum - Fatal编程技术网

R-具有不同列的矩阵的和列表

R-具有不同列的矩阵的和列表,r,matrix,sum,R,Matrix,Sum,我有一个包含不同列的大型矩阵列表,如果一个矩阵中不存在列X,我想将这些矩阵相加为0 如果您使用了plyr的函数rbind.fill,我想要类似的函数,但带有sum函数。当然,我可以构建一个函数来实现这一点,但由于我的数据量很大,我正在考虑使用Frotrain或C高效编程的本机函数 这里有一个例子: 这是一个简单的示例,其中我有相同的列: aa <- list( m1 = matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, dimnames = list(c(1

我有一个包含不同列的大型矩阵列表,如果一个矩阵中不存在列X,我想将这些矩阵相加为0

如果您使用了plyr的函数
rbind.fill
,我想要类似的函数,但带有sum函数。当然,我可以构建一个函数来实现这一点,但由于我的数据量很大,我正在考虑使用Frotrain或C高效编程的本机函数

这里有一个例子: 这是一个简单的示例,其中我有相同的列:

aa <- list(
  m1 = matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, dimnames = list(c(1,2,3),c('a','b','c'))),
  m2 = matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, dimnames = list(c(1,2,3),c('a','b','c')))
)
aa
Reduce('+',aa)
根据我的数据:

bb <- list(
  m1 = matrix(c(1,2,3,7,8,9), nrow = 3, dimnames = list(c(1,2,3),c('a','c'))),
  m2 = matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, dimnames = list(c(1,2,3),c('a','b','c')))
)
bb
Reduce('+',bb)
非常感谢

Xevi

一个选项是

un1 <- sort(unique(unlist(lapply(bb, colnames))))
bb1 <- lapply(bb, function(x) {
    nm1 <- setdiff(un1, colnames(x))
    m1 <- matrix(0, nrow = nrow(x), ncol = length(nm1), dimnames = list(NULL, nm1))
    cbind(x, m1)[, un1]})
> bb
$m1
  a c
1 1 7
2 2 8
3 3 9

$m2
  a b c
1 1 4 7
2 2 5 8
3 3 6 9
un1 <- sort(unique(unlist(lapply(bb, colnames))))
bb1 <- lapply(bb, function(x) {
    nm1 <- setdiff(un1, colnames(x))
    m1 <- matrix(0, nrow = nrow(x), ncol = length(nm1), dimnames = list(NULL, nm1))
    cbind(x, m1)[, un1]})
Reduce(`+`, bb1)
#   a b  c
# 1 2 4 14
# 2 4 5 16
# 3 6 6 18