我有一个这种形式的 3D 数组
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
)应用到数组的每个“层”的每一列。
MyFun
接受一个参数,它是一个包含 9 个数字的向量(即这里的数组行),它对其进行一些操作。该功能可能类似于:
MyFun<- function(vect=NULL){
res<-sum(10+vect)
return(res)
}
基本上,我想应用 MyFun
在“扰动”和“复制”这两个维度(即分别为列和第 3 个维度)之间循环。如:
MyFun(vect=pert[,1,1])
MyFun(vect=pert[,2,1])
MyFun(vect=pert[,3,1])
MyFun(vect=pert[,4,1])
MyFun(vect=pert[,1,2])
MyFun(vect=pert[,2,2])
等等。
有没有一种方法可以在一次调用中使用 apply 来执行此操作,或者我应该嵌套 2 个 apply 函数(即一个循环通过列,另一个在第 3 个维度上循环)?
最佳答案
我们可以使用 apply
并将 MARGIN
指定为 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
关于r - 应用函数循环遍历 R 中数组的 3 个维度中的 2 个维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59146766/