R总和包含NaN的矩阵列表

我有以下矩阵列表,其中一个是na矩阵

l <- list(structure(c(-0.345207968896003,             -0.106294281751886,
 -0.106294281751886,   -0.0327278202985066),   .Dim  =   c(2L,   2L),
 .Dimnames    =    list(c("cst",     "HHI"),    c("cst",    "HHI"))),
 structure(c(1.15139745442976e-05,              3.68766982139475e-06,
 3.68766982139475e-06,  1.15176322872764e-06  ),  .Dim =  c(2L,  2L),
 .Dimnames    =    list(c("cst",     "HHI"),    c("cst",    "HHI"))),
 structure(c(NaN, NaN, NaN, NaN), .Dim = c(2L, 2L), .Dimnames = list(
 c("cst",            "HHI"),            c("cst",            "HHI"))),
 structure(c(-7.27547318293674e-83,            -2.19548052580106e-83,
 -2.19548052580106e-83,  -7.02352060565763e-84 ),  .Dim =  c(2L, 2L),
 .Dimnames    =    list(c("cst",     "HHI"),    c("cst",    "HHI"))),
 structure(c(4.87470592316947e-170,            1.84511037510365e-170,
 1.84511037510365e-170,  6.6824969949533e-171), .Dim  =  c(2L, 2L  ),
 .Dimnames = list(c("cst",  "HHI"), c("cst", "HHI"))), structure(c(0,
 0,  0, 0),  .Dim  =  c(2L, 2L),  .Dimnames  = list(c("cst",  "HHI"),
 c("cst", "HHI"))))

我想使用Reduce来汇总所有矩阵.

 a <-Reduce('+',l)

如何总结除去NaNs的基质?

最佳答案 我们可以用0替换NA值并使用Reduce

Reduce(`+`,lapply(l, function(x) replace(x, which(is.na(x)), 0)))
#           cst         HHI
#cst -0.3451965 -0.10629059
#HHI -0.1062906 -0.03272667

或者,如果您需要删除所有NA的列表元素

Reduce(`+`,l[!colSums(sapply(l, is.na))])
#           cst         HHI
#cst -0.3451965 -0.10629059
#HHI -0.1062906 -0.03272667

或另一种选择是融化/烤制

library(reshape2)
acast(melt(l, na.rm=TRUE), Var1~Var2, value.var='value', sum)
#          cst         HHI
#cst -0.3451965 -0.10629059
#HHI -0.1062906 -0.03272667

或者我们可以将它转换为数组,并通过使用apply指定MARGIN来获取sum或rowSums

 apply(array(unlist(l), c(dim(l[[1]]), length(l)), 
      dimnames=c(dimnames(l[[1]]), NULL)), 1, rowSums, na.rm=TRUE)
 #          cst         HHI
 #cst -0.3451965 -0.10629059
 #HHI -0.1062906 -0.03272667

apply(array(unlist(l),c(dim(l[[1]]), length(l)),
      dimnames=c(dimnames(l[[1]]), NULL)), c(1,2), sum, na.rm=TRUE)
#         cst         HHI
#cst -0.3451965 -0.10629059
#HHI -0.1062906 -0.03272667
点赞