r - 应用函数循环遍历 R 中数组的 3 个维度中的 2 个维度

标签 r arrays loops vectorization apply

我有一个这种形式的 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/

相关文章:

能否更高效地编写此图案打印算法?

r - r中数据框的名称

r - 使用带有替换函数的 get()

arrays - 从 csv 文件加载矩阵 - golang

python - 如何使用 numpy mggrid 或 meshgrid 来完成这个简单的任务

r - 在 R 中创建一个变量并添加到循环中的数据框

r - cbind警告:从短变量中找到了行名,并且已将其丢弃

r - 如何解决此错误 : attempt to set 'rownames' on an object with no dimensions

arrays - Mongoose 更新与对数组的推送操作和对对象的设置操作

javascript - 循环访问 classList 时无法编辑它