Hello,

Try using ?lapply, its return value is a list. Note however that the *apply functions are loops in disguise. There's nothing wrong with your solution to the problem, but it's true that most R users find lapply more elegant, like you say.

hold <- lapply(1:5, function(x) matrix(rnorm(4),2,2) )

Hope this helps,

Rui Barradas

Em 09-11-2016 18:32, Evan Cooch escreveu:
So, its easy enough to create a random matrix, using something like (say)

matrix(rnorm(4),2,2)

which generates a (2x2) matrix with random N(0,1) in each cell.

But, what I need to be able to do is create a 'list' of such random
matrices, where the length of the list (i.e., the number of said random
matrices I store in the list) is some variable I can pass to the
function (or loop).

I tried the obvious like

hold <- list()
for (i in 1:5) {
     hold[[i]] <- matrix(rnorm(4),2,2)
     }


While this works, it seems inelegant, and I'm wondering if there is a
better (more efficient) way to accomplish the same thing -- perhaps
avoiding the loop.

Thanks in advance...

______________________________________________
R-help@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.

______________________________________________
R-help@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.

Reply via email to