GFa*_*ien 7 r subset multidimensional-array tensor
想象一下,我在 R 中有一个 N 维数组(矩阵将是一个 2 维数组),我想从数组的 1 到 n 中选择行。我想知道在 R 中是否有一种语法可以在不知道维数的情况下做到这一点。确实,我可以
x = matrix(0, nrow = 10, ncol = 2)
x[1:5, ] # to take the 5 first rows of a matrix
x = array(0, dim = c(10, 2, 3))
x[1:5, , ] # to take the 5 first rows of a 3D array
Run Code Online (Sandbox Code Playgroud)
到目前为止,我还没有找到一种方法来使用这种写法来提取数组的行而不知道它的维数(显然,如果我知道维数,我只需要根据需要输入尽可能多的逗号)。以下代码段有效,但似乎不是最原生的方法:
x = array(0, dim = c(10, 2, 3, 4)
apply(x, 2:length(dim(x)), function(y) y[1:5])
Run Code Online (Sandbox Code Playgroud)
有没有更多的 R 方法来实现这一目标?
实际上,您的应用解决方案是最好的。
apply(x, 2:length(dim(x)), `[`, 1:5)
Run Code Online (Sandbox Code Playgroud)
甚至更好,正如@RuiBarradas 指出的那样(也请投票给他的评论!):
apply(x, -1, `[`, 1:5)
Run Code Online (Sandbox Code Playgroud)
来自 Lisp,我可以说,R 非常 lispy。而apply解决方案是一个非常lispy解决方案。因此它非常 R-ish(遵循函数式编程范式的解决方案)。