r 以编程方式确定的维度的数组切片 [英] r array-slice of programmatically determined dimension
问题描述
有没有一种方法可以在 R 中优雅地指定多维数组中的切片,从而事先不知道维数?
Is there a way of elegantly specify a slice in a multidimensional array in R, whereby the number of dimensions is not known beforehand?
例如,对于 5 维数组,可以使用
For instance, for a 5-dimensional array, slicing out the last dimension can be done using
fourdimslice <- fivedimarray[,,,,1]
但我想为任意维度编写代码,例如
but I'l like to code this for arbitrary dimensions, something like
slice <- arbitrarydimarray(dim=5, index=1)
我一直无法理解 do.call('[', ...)
是否是一种方法.我也试过命名维度,但 a[fifth=1]
没有按照我想要的方式解释.
I've not been able to understand if do.call('[', ...)
would be an approach. I've also tried named dimensions, but a[fifth=1]
is not interpreted the way I would want here.
我想像 apply()
这样的函数需要做类似的事情.
I suppose functions like apply()
need to do similar things.
推荐答案
您可以使用 asub
,来自 abind
包.
You can use asub
, from the abind
package.
# Sample data: a 5-dimensional array
x <- array(seq_len(prod(2:6)), dim=2:6)
library(abind)
str( asub(x, 1, 5) )
# int [1:2, 1:3, 1:4, 1:5] 1 2 3 4 5 6 7 8 9 10 ...
str( x[,,,,1] )
# int [1:2, 1:3, 1:4, 1:5] 1 2 3 4 5 6 7 8 9 10 ...
all( asub(x, 1, 5) == x[,,,,1] )
# [1] TRUE
这篇关于r 以编程方式确定的维度的数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!