Initialize a list of matrices in R

10,401

Solution 1

Also try this wrapper of *apply:

replicate(10, diag(2), simplify=F)

Solution 2

This one liner should work

rep(list(diag(2)), 10)

If you want the contents of the matrices to vary, then something like

lapply(1:10, function(x) matrix(1:x^2, x, x)

will be more appropriate. The contents of the anonymous function will obviously be something a bit more useful than my example, but the principle is the same

Solution 3

Both replicate and rep have been recommended. FYI: The difference is the evaluation of the expression being passed. 'rep' evaluates it's arguments as input, whereas 'replicate' evaluates them inside the 'loop'.

You can see this with random numbers. With replicate the numbers are different because the expression 'diag(rnorm(2))' is evaluated multiple times, whereas with rep, it's only evaluated once and the value is repeated.

rep(list(diag(rnorm(2))),2)

[[1]]

  [,1]    [,2]

[1,] 1.0844 0.0000

[2,] 0.0000 -2.3457

[[2]]

  [,1]    [,2]

[1,] 1.0844 0.0000

[2,] 0.0000 -2.3457

replicate(2,diag(rnorm(2)))

, , 1

   [,1]    [,2]

[1,] 0.42912 0.00000

[2,] 0.00000 0.50606

, , 2

    [,1]     [,2]

[1,] -0.57474 0.00000

[2,] 0.00000 -0.54663

This may or may not matter for you, but there are performance implications.

system.time(replicate(1000, diag(100),simplify=F))

user system elapsed

0.640 0.032 0.674

system.time(rep(list(diag(100)),1000))

user system elapsed

0.072 0.036 0.111

Solution 4

Try

lapply(1:10, diag, 2)

In your for loop you had to write [[ in output_array[[i]] = diag(2)

Share:
10,401
Michael
Author by

Michael

Updated on June 13, 2022

Comments

  • Michael
    Michael almost 2 years

    I was wondering if there's a quick way to initialize a list of matrices in R. For example I'm looking for a (one-liner) to reproduce the same results as the following:

    output_array = list()
    for(i in 1:10){
    output_array[i] = diag(2)
    }
    

    Thanks!

  • Matthew Plourde
    Matthew Plourde over 11 years
    you definitely want simplify=FALSE in there.