在for循环中,我在i
上运行一个数组,我希望在维i
中进行子索引。如何才能做到这一点?所以最小的例子是
(A <- array(1:24, dim = 2:4))
A[2,,] # i=1
A[,1,] # i=2
A[,,3] # i=3
我用脚指数&#39;。我尝试了类似this的内容,但并未取得成功。当然有人可以创造&#34; 2 ,,&#34;作为一个字符串然后eval&amp;解析代码,但那很难看。此外,在for循环内部(i
之上),我可以使用aperm()
置换数组,使新的第一个维度为前i
,这样我就可以简单地访问第一部分。但那种丑陋也需要将阵列置换回来。任何想法如何更像R /优雅?
实际问题是多维table()
对象,但我认为这个想法将保持不变。
更新
我接受了里克的回答。我只是用for循环呈现它并进一步简化它:
subindex <- c(2,1,3) # in the ith dimension, we would like to subindex by subindex[i]
for(i in seq_along(dim(A))) {
args <- list(1:2, 1:3, 1:4)
args[i] <- subindex[i]
print(do.call("[", c(list(A), args)))
}
答案 0 :(得分:2)
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array
indexNumber = 2
indexSelection = 1
# Build a parameter list indexing all the elements of A
parameters <- list(A, 1:2, 1:3, 1:4)
# Modify the appropriate list element to a single value
parameters[1 + indexNumber] <- indexSelection
# select the desired subarray
do.call("[", parameters)
答案 1 :(得分:0)
# Now for something completely different!
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array
indexNumber = 2
indexSelection = 1
reduced <- A[slice.index(A, indexNumber) == indexSelection]
dim(reduced) <- dim(A)[-indexNumber]
# Also works on the left-side
A[slice.index(A, 2)==2] <- -1:-8