通过R中数组的3维中的2维应用函数循环

时间:2019-12-02 21:15:12

标签: r arrays loops vectorization apply

我有这种形式的3D阵列

<a href="#">
  <span class="aSpan">
       <div>Not this</div>
         This
      </span>
</a>

,并且我想对数组的每个“层”的每一列应用一个函数(例如n_rep<-1000 n_box<-9 pert<-array(,dim=c(9,4,n_rep), dimnames=list(box=LETTERS[1:n_box],perturbation=c('p1','p2','p3','p4'),replicate=1:n_rep)) set.seed(1235) pert[,1,]<-round(runif(n_rep*n_box,-1,1),0) pert[,2,]<-round(runif(n_rep*n_box,-2,2),0) pert[,3,]<-round(runif(n_rep*n_box,-3,3),0) pert[,4,]<-round(runif(n_rep*n_box,-4,4),0) )。 MyFun接受一个参数,该参数是9个数字(在此为数组的行)的向量,对其进行操作。该功能可能类似于:

MyFun

因此,基本上,我想在“摄动”和“复制”这两个维度(即分别为列和第3维)上应用MyFun<- function(vect=NULL){ res<-sum(10+vect) return(res) } 循环。如:

MyFun

还有堡垒。

是否有一种方法可以在一次调用中使用apply来执行此操作,还是我应该嵌套2 Apply函数(即,一个通过列提示,另一个在第3维维度)?

1 个答案:

答案 0 :(得分:1)

我们可以将applyMARGIN一起指定为2和3

out <- apply(pert, c(2, 3), FUN = MyFun)

也可以使用嵌套循环

out1 <- t(sapply(seq_len(dim(pert)[2]), function(j) 
       sapply(seq_len(dim(pert)[3]), function(k) MyFun(pert[, j, k]))))
all.equal(out, out1, check.attributes = FALSE)
#[1] TRUE

-检查

identical(out[1,1], MyFun(vect=pert[,1,1]))
#[1] TRUE
identical(out[4,1], MyFun(vect=pert[,4,1]))
#[1] TRUE

identical(out[2,2], MyFun(vect=pert[,2,2]))
#[1] TRUE