[R] naming rows/columns in 'array of matrices' | solved

Evan Cooch evan.cooch at gmail.com
Fri Jan 30 20:34:20 CET 2015


The (obvious, after the fact) solution at the bottom. D'oh...

On 1/30/2015 2:07 PM, Evan Cooch wrote:
> Suppose I have the following situation:
>
> I have an array of 2 matrices, where each matrix is (2x2):
>
> P <- array(0, c(2,2,2))
>
> P[,,1] <- matrix(c(1,2,3,4),2,2,byrow=T);
> P[,,2] <- matrix(c(5,6,7,8),2,2,byrow=T);
>
> I want to label rows and columns of each matrix in the array, such 
> that P would look like
>
>
>         live dead
> live      1    2
> dead      3    4
>
> , , 2
>
>         live  dead
>  live     5    6
>  dead     7    8
>
> I've tried 'direct, brute force" approaches like
>
> rownames(P[,,1]) <- c("live","dead")
> colnames(P[,,1]) <- c("live","dead")
>
> (repeated for the second matrix), but this doesn't work.
>
> Since all of the matrices are of the same dimension(s), and since I 
> want the same rownames and colnames for each matrix, I'm hoping there 
> is some simply magical permutation of lapply (I'm guessing) which will 
> do the trick.

Forgot I was dealing with a multi-dimensional array, not a list. So, 
following works fine. I'm sure there are better approaches (where 
'better' is either 'cooler', or 'more flexible'), but for the moment...)

P <- array(0, 
c(2,2,2),dimnames=list(c("live","dead"),c("old","young"),NULL))

P[,,1] <- matrix(c(1,2,3,4),2,2,byrow=T);
P[,,2] <- matrix(c(5,6,7,8),2,2,byrow=T);

print(P);



More information about the R-help mailing list