[R] How to name matrices from a list with lapply ?

Gabor Grothendieck ggrothendieck at gmail.com
Tue Aug 3 18:00:58 CEST 2010


On Tue, Aug 3, 2010 at 11:42 AM, Carlos Petti <carlos.petti at gmail.com> wrote:
> Dear list,
>
> I have a list of matrices :
>
> i1 <- matrix(1:10, nrow = 2, ncol = 5)
> i2 <- matrix(11:20, nrow = 2, ncol = 5)
> j <- list(i1 = i1, i2 = i2)
>
> I would like to attribute names to each dimension, for each matrix,
> as follows :
>
> $i1
> B1 B2 B3 B4 B5
> A1 1 3 5 7 9
> A2 2 4 6 8 10
>
> $i2
> B1 B2 B3 B4 B5
> A1 11 13 15 17 19
> A2 12 14 16 18 20
>
> However, I have to use lapply function and attribute names
> after declaration of j, like this :
>
> names <- list(c("A1", "A2"), c("B1", "B2", "B3", "B4", "B5"))
> lapply(j, function (x) {dimnames(x) <- names})
> or
> lapply(j, function (x) {as.matrix(x, dimnames = names)})
>
> But, it does not work.
>
> I can use : lapply(j, function (x) {matrix(x, nrow = 2, ncol = 5, dimnames =
> names)})
>

Try this:

   lapply(j, structure, dimnames = names)



More information about the R-help mailing list