Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.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 带NAs的矩阵和列表_R_Matrix - Fatal编程技术网

R 带NAs的矩阵和列表

R 带NAs的矩阵和列表,r,matrix,R,Matrix,我希望计算矩阵和,并忽略包含的任何NAs,如以下示例所示: x1 <- matrix(c(NA,NA,2,2),2,2) x2 <- matrix(c(NA,3,NA,NA),2,2) x3 <- matrix(c(NA,NA,NA,NA),2,2) x4 <- matrix(c(1,2,3,4),2,2) lx <- list(x1,x2,x3,x4) Reduce('+',lx) # does not work because of NAs result &l

我希望计算矩阵和,并忽略包含的任何NAs,如以下示例所示:

x1 <- matrix(c(NA,NA,2,2),2,2)
x2 <- matrix(c(NA,3,NA,NA),2,2)
x3 <- matrix(c(NA,NA,NA,NA),2,2)
x4 <- matrix(c(1,2,3,4),2,2)
lx <- list(x1,x2,x3,x4)
Reduce('+',lx) # does not work because of NAs

result <- matrix(c(1,5,5,6),2,2)

如何做到这一点?

我们可以编写一个自定义函数,并在
Reduce
中使用它。我们将
NA
s替换为0,然后添加它们

modifiedSum <- function(x, y) {
  replace(x, is.na(x), 0) + replace(y, is.na(y), 0)
}

Reduce(modifiedSum, lx)

#     [,1] [,2]
#[1,]    1    5
#[2,]    5    6

modifiedSum
apply(simplify2array(lx),1:2,sum,na.rm=TRUE)
Ok以前从未见过这个
simplify2array
。如果你能解释这背后的原因,那么也许值得你回答。从中,我不确定这是否应该是一个副本。我怀疑这是一个重复的bec,所以没有一个线程专门处理NAs。通常使用的带有
Reduce
的解决方案也不起作用。但不管怎样,答案是肯定的。
modifiedSum <- function(x, y) {
  replace(x, is.na(x), 0) + replace(y, is.na(y), 0)
}

Reduce(modifiedSum, lx)

#     [,1] [,2]
#[1,]    1    5
#[2,]    5    6