[R] Array analogue of row and col

Duncan Murdoch murdoch.duncan at gmail.com
Tue Apr 2 14:28:07 CEST 2013


On 02/04/2013 6:36 AM, Enrico Bibbona wrote:
> Is there any function that extends to multidimentional arrays the
> functionalities of "row" and "col" which are just defined for matrices?
> Thanks, Enrico Bibbona

Not as far as I know, but there are a lot of functions in packages.

You could write your own something like this.  I've skipped any error 
checking; you'll want to add that.

indices <- function(a, which) {
   d <- dim(a)
   prod_before <- prod(d[seq_len(which-1)])
   result <- rep(seq_len(d[which]), each=prod_before,  length.out = prod(d))
   dim(result) <- d
   result
}

Then indices(a, 1) gives an array of the same shape as a where entry i, 
j, k, ... is i, indices(a, 2) has entry i,j,k, ... equal to j, etc.

Duncan Murdoch



More information about the R-help mailing list