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

Adams, Jean jvadams at usgs.gov
Mon Feb 2 14:59:59 CET 2015


In your example, P is a three dimensional array.  You can assign names to
the three dimensions using the dimnames() function.  For example, this
command assigns names to the first two dimensions, but leaves the third
dimension without names.

dimnames(P) <- list(c("live", "dead"), c("live", "dead"), NULL)

Jean

On Fri, Jan 30, 2015 at 1:07 PM, Evan Cooch <evan.cooch at gmail.com> 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.
>
>  I'd also be interested in why the 'direct, brute force' approach (above)
> doesn't work, and what does, since I might need to manipulate row/col names
> for individual matrices in the array (if, say, dimensions of the matrices
> were not the same over the array).
>
> Thanks in advance!
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list