假设您在R中具有n维,同构数据结构(数组),其中包含可变但固定数量的维度:
n_dim <- 3
n_row <- 3
a <- array(seq(n_row ^ n_dim), dim = rep(n_row, n_dim))
a
>, , 1
>
> [,1] [,2] [,3]
>[1,] 1 4 7
>[2,] 2 5 8
>[3,] 3 6 9
>[..]
是否有一种简单的语法来访问给定维度的下标,而不是计算来自n_dim
的逗号或使用1-Dim位置计算位置a[c(1,...)]
?是否有提供此功能的a[get row in dim]
方法?
# Give me the 1st row of the "last" dimension
expr <- paste0("a[",
paste0(rep(", ", n_dim - 1), collapse = ""),
x,
"]")
expr
> [1] "a[, , 1]"
eval(parse(text = expr))
> [,1] [,2] [,3]
>[1,] 1 4 7
>[2,] 2 5 8
>[3,] 3 6 9
谢谢!
答案 0 :(得分:3)
一个选项是abind
library(abind)
asub(a, 1, n_dim)
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9