简体   繁体   English

R:使用Mapply来避免循环

[英]R: Using Mapply to avoid loop

I have following code which I perform with for loop to generate a 3D array "newarr". 我有以下代码,我执行for循环生成3D数组“newarr”。

n1<-c(1,2,3,4,5)
n2<-c(3,4,5,6,7)
n3<- c(4,5,6,7,8)

afun <- function(y,p,q,r){
              calc=1/(1+(((y-p)/q)^(2*r)))
              return(calc)
        }

newarr<- array(dim = c(4,5,5))
Amat<-matrix(data=c(1:10,NA,NA,NA,NA,15:20),nrow = 4,ncol = 5)
Bmat<-matrix(data=c(1:6,NA,NA,NA,NA,11:20),nrow = 4,ncol = 5)
Qmat<- +(!is.na(Amat) & !is.na(Bmat))

for(i in 1:5){
     res<-afun(Amat,n1[i],n2[i],n3[i])
     newarr[,,i]<- res 
}

I want to use Mapply (or any apply function) instead of for loop. 我想使用Mapply (或任何apply函数)而不是for循环。 arr2 <- array((mapply(function(x,y,n1,n2,n3) if(x==1) afun(y,n1,n2,n3) else 0,Qmat,Amat,n1,n2,n3)),c(4,5,5)) arr2 < - array((mapply(function(x,y,n1,n2,n3)if(x == 1)afun(y,n1,n2,n3)else 0,Qmat,Amat,n1,n2,n3) ),C(4,5,5-))

The following code seems to help but without condition as described further: 以下代码似乎有所帮助,但没有进一步描述的条件:
newarr <- array(mapply(afun, n1,n2,n3, MoreArgs = list(y=Amat)), c(4,5,5)) newarr < - array(mapply(afun,n1,n2,n3,MoreArgs = list(y = Amat)),c(4,5,5))

I want to include a condition by using Qmat (a 4x5 matrix with 0 and 1), so that when '0' is observed, no operation should be performed and return '0'value to fill matrix. 我想通过使用Qmat(一个带有0和1的4x5矩阵)来包含一个条件,这样当观察到'0'时,不应该执行任何操作并返回'0'值来填充矩阵。 For 1s in Qmat, perform 'afun' function and return the value to "newarr" to form a 3D matrix. 对于Qmat中的1,执行'afun'函数并将值返回到“newarr”以形成3D矩阵。

Thanks for the help!! 谢谢您的帮助!!

This will give you the desired result: 这将为您提供所需的结果:

newarr <- array(mapply(afun, n1,n2,n3, MoreArgs = list(y=Amat)), c(4,5,5))

this is using the implicit SIMPLIFY=TRUE of mapply(). 这是使用mapply()的隐式SIMPLIFY = TRUE。 With SIMPLIFY=TRUE each result is reduced to a vector. 使用SIMPLIFY = TRUE时,每个结果都会减少为向量。 (a matrix is a vector with a dimension attribute) (矩阵是具有维度属性的向量)
Another variant is 另一种变体是

array(unlist(mapply(afun, n1,n2,n3, MoreArgs = list(y=Amat), SIMPLIFY = FALSE)), c(4,5,5))

here you will get a list of matrices as result from mapply(). 在这里,您将获得mapply()的结果列表。 You have to unlist. 你必须取消上市。

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

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