[R] storing matrix(variables) in loop

Benilton Carvalho beniltoncarvalho at gmail.com
Mon Mar 15 16:03:48 CET 2010


If you could describe exactly what is it that you're trying to
accomplish, we could be of better help (the reason I say this is
because the way you're trying to implement things is a bit
inefficient).

Anyways, you can't use two indices with a list.

One approach would be to nest lists, and you'd get to extract elements
using calls like b[[i]][[j]]. The example below shows an example, but
it can be greatly improved depending on your specific scenario

f <- function(.x) lapply(1:4, function(.x) matrix(runif(1), 3, 3))
b <- lapply(1:3, f)

b[[1]][[2]]


--benilton

2010/3/15 Márcio Resende <mresendeufv at yahoo.com.br>:
>
> Hello R-helpers,
> I have the following code that works well,
>
> b <-list()
> for (i in 1:3){
> a <- matrix(runif(1),3,3)
> b[[i]] <- a
> }
> b
>
> however, I need to do something similar with two loops and I was looking for
> something that would look like
>
> b <- list()
> for (i in 1:3){
> for (j in 1:4){
> a <- matrix(runif(1),3,3)
> b[[i,j]] <- a #but this doesn´t work
> }
> }
>
> Anyway, I wanted "b" to loop like
> [[i=1, j=1]]         [[i=1, j=2]]     (...)
> a[i=1, j=1]           a[i=1,j=2]      (...)
>
> [[i = 2, j=1]]    (...)
> a[i = 2, j = 1]   (...)
>
> (...)
>
> Can anybody help me?
> Thanks
>
> --
> View this message in context: http://n4.nabble.com/storing-matrix-variables-in-loop-tp1593461p1593461.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



More information about the R-help mailing list