开发者

How to get column index matrix of an array in R?

开发者 https://www.devze.com 2023-03-22 01:02 出处:网络
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))

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.

开发者_StackOverflow

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" 


The function is just

colmtx <- function(x, n) {  return( array( 
                   rep(dimnames(x)[[n]], each=prod(dim(x)[0:(n-1)])), 
                   dim=dim(x) ) ) }


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)
         }

}


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))
  })
}
0

精彩评论

暂无评论...
验证码 换一张
取 消