2

Imagine I have a simple 4x3x2 array in R.

> x <- array(1:24,c(4,3,2), dimnames=list(c('a','b','c','d'),c('x','y','z'),1:2))
>  x
, , 1

  x y  z
a 1 5  9
b 2 6 10
c 3 7 11
d 4 8 12

, , 2

   x  y  z
a 13 17 21
b 14 18 22
c 15 19 23
d 16 20 24

What I'd like, is a simple function on the array that gives me back the name of the index of each element for an arbitrary dimension. In this case, dimension 2.

The function would behave like this:

> arraydims(x,2)  #Where 2 is dimension I want names for.

, , 1

     [,1] [,2] [,3]
[1,] "x"  "y"  "z" 
[2,] "x"  "y"  "z" 
[3,] "x"  "y"  "z" 
[4,] "x"  "y"  "z" 

, , 2

     [,1] [,2] [,3]
[1,] "x"  "y"  "z" 
[2,] "x"  "y"  "z" 
[3,] "x"  "y"  "z" 
[4,] "x"  "y"  "z" 
evanrsparks
  • 363
  • 3
  • 13

3 Answers3

4

The function is just

colmtx <- function(x, n) {  return( array( 
                   rep(dimnames(x)[[n]], each=prod(dim(x)[0:(n-1)])), 
                   dim=dim(x) ) ) }
IRTFM
  • 258,963
  • 21
  • 364
  • 487
0

I think this works as intended. My coding is probably a bit dodgy at best and there may well be a more straightforward solution.

arraydims <- function(arrname,arrdim) {

#rows

if(arrdim==1) {
arrname[,,] <- dimnames(arrname)[[1]]
print(arrname)
         }

#columns

if(arrdim==2) {
arrname[,,] <- rep(dimnames(arrname)[[2]],each=dim(arrname)[1])
print(arrname)
         }

#tables   

if(arrdim==3) {
arrname[,,] <- rep(dimnames(arrname)[[3]],each=dim(arrname)[1]*dim(arrname)[2])
print(arrname)
         }

}
thelatemail
  • 91,185
  • 12
  • 128
  • 188
0

Here's another way to do it. It gets the names for all dimensions at once (though that could be changed; I did it that way because the which returned all the indices anyway.

arraydims <- function(x) {
  x[] <- 1
  idx <- which(x==1, arr.ind=TRUE)
  lapply(1:ncol(x), function(k) { 
    array(dimnames(x)[[k]][idx[,k]], dim(x), dimnames=dimnames(x))
  })
}
Aaron left Stack Overflow
  • 36,704
  • 7
  • 77
  • 142