[R] storing matrices in a list or vector and preserve dimensions
Gabor Csardi
csardi at rmki.kfki.hu
Tue Jan 8 15:17:33 CET 2008
Bram,
On Tue, Jan 08, 2008 at 03:11:07PM +0100, Bram Kuijper wrote:
> Hi all,
>
> As an R newbie, I wonder how I can store multiple matrices in a list()
> or vector() object without losing their structure. I should be able to
> retrieve the matrix from the list later on.
>
> If I just append() the matrices to a list() object, they automatically
> lose their dimensions, whereas I would like to preserve the dimensions
> of the matrices.
append concatenates two list (as far as i can remember), but not a
list and a list element. A simple workaround is to use
l <- append(l, list(e))
instead of
l <- append(l, e)
> Is there any function in R which allows me to store a _fully preserved_
> object inside a list() or vector() structure?
You can also do things like
l <- list(1,2,3)
l[[2]] <- 5
l[[10]] <- matrix(runif(100), 10, 10)
etc. For more you should really read 'Introduction to R',
see the documentation links on the R homepage.
Gabor
> thanks in advance,
>
> Bram Kuijper
>
>
>
>
> PS: this is what I do:
>
> # two matrices, which are my objects to be put in the list
> my_matrix_object1 <- matrix(data=rep(1,times=9),nrow=3,ncol=3);
> my_matrix_object2 <- matrix(data=rep(0,times=9),nrow=3,ncol=3);
>
> my_list <- list()
> # note that I explicitly want to append the object to the list
> # instead of directly inserting it from the beginning
> # (e.g., code to be used in a for-loop)
> my_list <- append(my_list,as.matrix(my_matrix_object1));
> my_list <- append(my_list,as.matrix(my_matrix_object2));
>
> However, this results in the following list structure...
> [[1]]
> [1] 1
>
> [[2]]
> [1] 1
>
> [[3]]
> [1] 1
>
> ... etcetera,
>
> whereas I just want to preserve the matrix structure in my list:
>
> my_matrix_object1;
> [,1] [,2] [,3]
> [1,] 1 1 1
> [2,] 1 1 1
> [3,] 1 1 1
> ,
> [,1] [,2] [,3]
> [1,] 0 0 0
> [2,] 0 0 0
> [3,] 0 0 0
>
> I guess I need a more sophisticated function then append, but I do not
> know which one?
>
> ______________________________________________
> 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.
--
Csardi Gabor <csardi at rmki.kfki.hu> MTA RMKI, ELTE TTK
More information about the R-help
mailing list