【发布时间】:2021-05-28 05:18:45
【问题描述】:
假设我们有一个像这样的 3 维数组
a <- array(1:24, dim = c(4, 3, 2))
访问或索引数组通常通过
# fixing the third (=last) dimension and output the corresponding values of the first and second dimension
a[, , 1]
> a
, , 1
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
在这个例子中,我知道维数是 3。因此,我可以手动输入两个逗号,后跟最后一个维度的数字(此处为 1)。但是现在我想通过先验地固定最后一个维度而不知道维度的数量来创建一个用于动态索引数组的表达式。此构造稍后应在循环中使用,例如lapply().
dims <- paste0(paste0(rep("", length(dim(a)) - 1L), collapse = ","), ",idx")
> dims
[1] ",,idx"
我是否能够将这个动态创建的字符串 ",,idx" 转换为任何内容 - 我知道索引本身并不是一个可用于索引的表达式?
a[dims] <- ... # won't work!
提前致谢!
【问题讨论】:
-
你到底想要这个做什么?你想完成什么?
-
@Onyambu 我想编写一个函数,该函数能够将一个数组插入到另一个数组中关于最后一个维度的某个位置。这是一种 abind() 但选择插入数组应出现的位置。
-
试试
do.call('[', c(list(a), rep(list(TRUE), length(dim(a))-1), 1)) -
@all 感谢您的快速回复!