R总和包含NaN的矩阵列表

时间:2015-07-26 13:43:21

标签: r

我有以下矩阵列表,其中一个是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)

如何对去除NaN的基质求和?

1 个答案:

答案 0 :(得分:2)

我们可以使用replace NA 0值并使用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

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

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

或另一个选项是melt/acast

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

或者我们可以将其转换为array并通过使用sum

指定rowSums来获取MARGINapply
 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