[R] Fwd: Empty list to use in a for cycle
Joerg van den Hoff
j.van_den_hoff at fzd.de
Mon Nov 26 18:28:25 CET 2007
On Mon, Nov 26, 2007 at 04:35:53PM +0100, Niccolò Bassani wrote:
> Dear R-users,
> I'm posting a problem I already asked help for some time ago, because I'm
> facing that problem once again and even because now, reading that old
> e-mail, and the answer recevied, I understand I've not made myself clear.
>
> Here's the question: I need to create an empty list of a specific length to
> fill it with a quite large amount of square matrices, which is 602. The
> question is that these matrices are created inside a for cycle, and I do not
> know how to recall all of them one by one, except by creating an empty list
> before the cycle, than assigning for each value of the i index the amtrix
> computed to the first element of the empty list.
> The fact is that: i've trided to create an empty list with
>
> vector("list",602)
>
> and then putting it in a cycle, but it didn't work. This is the cycle I've
> used. To prove it works (and then the cycle itself is not a problem) there's
> also the output (i.e. the last square matrix computed).
>
> for (i in unique(elio2$id)){
> sub.mu <- exp.mu[exp.mu$id==i,]
> D <- matrix(0,nrow( sub.mu),nrow(sub.mu))
> diag(D) <- sub.mu$deriv.link
> A <- mat.cov[1:nrow(D),1:nrow(D)]
> R <- corstr[1:nrow(D),1:nrow(D)]
> W <- solve(D)%*%solve(sqrt(A))%*%solve(R)%*%solve(sqrt(A))%*%solve(D)
> }
>
> > W
> [,1] [,2] [,3] [,4]
> [1,] 3.492489e+02 -7.9324883721 0.0006286788 -0.0031046240
> [2,] -7.932488e+00 17.4974625191 -1.7575467817 0.0001403319
> [3,] 6.286788e-04 -1.7575467817 17.3227959738 -1.7529916860
> [4,] -3.104624e-03 0.0001403319 -1.7529916860 17.2279244622
> >
>
> Does anyone knows how to insert each and every matrix like the one above in
> a "omnicomprehensive" list? That's because I've to use a function requiring
> me to have the matrices I need inside a list.
> Thanks in advance, hope it's not a too much stupid problem!
> niccol?
>
you seem to have all the ingredients, so where is the
problem? it's probably not really faster to preallocate this
(moderately long) list. so something like, e.g.
matlist <- list()
for (i in 1:3) {
matlist[[i]] = matrix(i, 2, 2)
}
should do what you want: create a list of matrices.
joerg
More information about the R-help
mailing list