lkegel
lkegel

Reputation: 303

Indexing and subscripts for R arrays with variable dimensions

Suppose you have an n-dimensional, homogeneous data structure (array) in R with a variable but fixed number of dimensions:

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
>[..]

Is there a simple syntax to access a subscript of a given dimension, instead of counting the commas from n_dim or counting the position with 1-dim positions a[c(1,...)]? Is there any a[get row in dim] method that provides this already?

# 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

Thank you!

Upvotes: 1

Views: 148

Answers (1)

akrun
akrun

Reputation: 887078

One option would be abind

library(abind)
asub(a, 1, n_dim)
#      [,1] [,2] [,3]
#[1,]    1    4    7
#[2,]    2    5    8
#[3,]    3    6    9

Upvotes: 4

Related Questions