在比较多维数组时替换循环

时间:2021-01-04 21:17:15

I am working with multi-dimensional arrays, and making comparisons for each element. So far, I have been using loops, but I was wondering how I could use apply(or another better function to avoid the loops). I am not sure ..I tried several ways, but it is not working fine.

我正在使用多维数组,并对每个元素进行比较。到目前为止,我一直在使用循环,但我想知道如何使用apply(或其他更好的函数来避免循环)。我不确定..我尝试了几种方法,但它没有正常工作。

Let's say the following example, where I compute the 95 percentile for the elements of the 3-dimension, and then I make a comparison:

让我们说下面的例子,我计算三维元素的95百分位数,然后我做一个比较:

       m <- array(1:30, c(5,4,3))
       mp <- apply(m,1:2,quantile,probs=c(.95),na.rm=TRUE) 
       temp      <- array(dim=dim(m))

       for(i in 1:5){
         for(j in 1:4){
            temp[i,j,] <- m[i,j,]>mp[i,j]
         }
       }

I don't know if apply can be used here(I read some posts but still not sure), is there any other way to avoid the loops??

我不知道申请是否可以在这里使用(我读了一些帖但但还不确定),还有其他方法可以避免循环吗?

Thanks in advance!

提前致谢!

1 个解决方案

#1


You can use vectorization and assigning dimensions after the evaluation of your condition:

在评估条件后,您可以使用矢量化并指定尺寸:

 array(as.vector(m)>as.vector(mp),dim(m))

#1


You can use vectorization and assigning dimensions after the evaluation of your condition:

在评估条件后,您可以使用矢量化并指定尺寸:

 array(as.vector(m)>as.vector(mp),dim(m))