简体   繁体   中英

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. 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?). So,

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

Is there a way to do this without a for loop? 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'

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

Checking with the OP's solution

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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