[R] repeating matrices in a list

Sarah Goslee sarah.goslee at gmail.com
Fri Nov 30 18:53:59 CET 2012


You are so close:

rep(list(g), 3)
[[1]]
     [,1] [,2] [,3]
[1,] 0.00  2.0    4
[2,] 0.25  0.0    0
[3,] 0.00  0.6    0

[[2]]
     [,1] [,2] [,3]
[1,] 0.00  2.0    4
[2,] 0.25  0.0    0
[3,] 0.00  0.6    0

[[3]]
     [,1] [,2] [,3]
[1,] 0.00  2.0    4
[2,] 0.25  0.0    0
[3,] 0.00  0.6    0


Sarah

On Fri, Nov 30, 2012 at 12:50 PM, Anser Chen <anser.chen at gmail.com> wrote:
> Suppose I have the following  square, non-negative matrices
>
>> g=matrix(c(0,2,4,0.25,0,0,0,0.6,0),3,3,byrow=T);
>
>
>
> I want to create a list where this matrix is repeated multiple times. if I
> do this brute force (manually), using
>
>> env <- list(g,g,g)
>
> works fine. Yields
>
> [[1]]
>      [,1] [,2] [,3]
> [1,] 0.00  2.0    4
> [2,] 0.25  0.0    0
> [3,] 0.00  0.6    0
>
> [[2]]
>      [,1] [,2] [,3]
> [1,] 0.00  2.0    4
> [2,] 0.25  0.0    0
> [3,] 0.00  0.6    0
>
> [[3]]
>      [,1] [,2] [,3]
> [1,] 0.00  2.0    4
> [2,] 0.25  0.0    0
> [3,] 0.00  0.6    0
>
>
>
> But - for a variety of purposes, I need to 'automate' building said list. I
> tried using rep
>
>
>>  env <- list(rep(g,each=3))
>
> but this yields
>
> [1] 0.00 0.00 0.00 0.25 0.25 0.25 0.00 0.00 0.00 2.00 2.00 2.00 0.00 0.00
> 0.00
> [16] 0.60 0.60 0.60 4.00 4.00 4.00 0.00 0.00 0.00 0.00 0.00 0.00
>
> Any suggestions/pointers to the obvious?
>
> Thanks in advance...


--
Sarah Goslee
http://www.functionaldiversity.org




More information about the R-help mailing list