简体   繁体   English

对3D阵列的每个第3维应用替换

[英]Apply a replacement to each 3rd dimension of a 3D array

I have an mxnxp (3D) array A. I have a 2D matrix B with values ranging from 1:m in the first column and 1:n in the second column. 我有一个mxnxp(3D)数组A。我有一个2D矩阵B,其值在第一列中为1:m,在第二列中为1:n。 What I'd like to do is NA out the indices that correspond to those given by B in each of the third dimension (heights?). 我想做的是在第三个维度(高度?)的每一个中对应于B给出的索引。 So, 所以,

for (i in 1:p) {
    A[,,i][B] = NA
}

Is there a way to do this without a for loop? 有没有没有for循环的方法? I was thinking something like 我在想类似

A_NA = apply(A,3,function(x) x[B] = NA)

But that doesn't work. 但这是行不通的。

We need to return the x and then assign it back to 'A' 我们需要返回x ,然后将其分配回'A'

A[] <- apply(A,3,function(x) { x[B] = NA; x})

Checking with the OP's solution 检查OP的解决方案

for (i in 1:p) {
     A1[,,i][B] = NA
 }

identical(A, A1)
#[1] TRUE

data 数据

A <- array(1:40, c(5, 4, 2) )
B <- cbind(c(1, 2, 3, 4), c(2, 3, 1, 1))
p <- 2
A1 <- A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM