[R] Splitting 3D matrix from for loop to generate/save 2D matrices

David Winsemius dwinsemius at comcast.net
Mon Nov 22 07:03:58 CET 2010

On Nov 22, 2010, at 12:27 AM, Hana Lee wrote:

> Hi!
> I have a matrix called M with dimension (586,100,100).

In R you have an array (not a matrix) wehn the number of dimensions is  

> I would like to split
> and save this into 586 matrices with dimension 100 by 100.

> I have tried the following for loops but couldn't get it work..
> l<-dim(M)[1]
> for (i in (1:l)){
> save(M[i,,],

I think the save function needs a name rather than an object for  
evaluation. Also it's not a representation that will be particularly  
useful outside the context of R.

> file = "M_[i].img")

# the R interpreter is not going to evaluate those "i"'s inside  
quotes, no matter how smart you think it is.

> }

Maybe (with some hesitation about the advisability of this):

for (i in (1:l)){
    temp <- M[i,,]
    save(temp, file = paste("M_",i",".img", sep="")

When these get load()-ed back in, they will each have the have "temp",  
so if you read in more than one, only the last one will remain. It  
might make more sense to write them out as a group and read them back  
in the same way.

> Can somebody help me with this? Thanks!
> Hana Lee
> 	[[alternative HTML version deleted]]

David Winsemius, MD
West Hartford, CT

More information about the R-help mailing list