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

Henrik Bengtsson hb at biostat.ucsf.edu
Mon Nov 22 06:56:10 CET 2010


Sorry, I did a mistake corrected below.

On Sun, Nov 21, 2010 at 9:50 PM, hb <hb at biostat.ucsf.edu> wrote:
> Hi,
>
> On Sun, Nov 21, 2010 at 9:27 PM, Hana Lee <hanalee at email.unc.edu> wrote:
>> Hi!
>>
>> I have a matrix called M with dimension (586,100,100).
>
> First of all, In R it is only an object with *two* dimensions that is called "matrix". Anything with two or more dimensions is called an "array". Example:
>
>> x <- 1:(2*3*4)
>> y <- matrix(x, ncol=2)
>> z <- array(x, dim=c(2,3,4))
>
> # VECTORS
>> is.vector(x)
> [1] TRUE
>> is.vector(y)
> [1] FALSE
>> is.vector(z)
> [1] FALSE
>
> # MATRICES
>> is.matrix(x)
> [1] FALSE
>> is.matrix(y)
> [1] TRUE
>> is.matrix(z)
> [1] FALSE
>
> # ARRAYS
>> is.array(x)
> [1] FALSE
>> is.array(y)
> [1] TRUE
>> is.array(z)
> [1] TRUE
>
> So, you've got an *array* (not a matrix).
>
>> 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,,],file = "M_[i].img")
>> }
>
> "...but couldn't get it work [as I wanted]."

Indeed save(M[i,,], ...) will throw an error.  You also need to subset
to a temporary variable, e.g. X <- M[i,,], and save that.  See below.

>
> The problem you have is generate a unique filename for matrix. The following two lines generate the same filename:
>
> filename <- sprintf("M_%d.img", i);
> filename <- paste("M_", i, ".img", sep="");
>
> I prefer to use the sprintf() version.
>
> So,
>
> l <- dim(M)[1]
> for (i in (1:l)) {
> filename <- sprintf("M_%d.img", i);
> save(M[i,,], file=filename);
> }
>

l <- dim(M)[1]
for (i in (1:l)) {
  filename <- sprintf("M_%d.img", i);
  X <- M[i,,];
  save(X, file=filename);
}


Note that this will load the data into a variable called 'X' when you
load() one of the files.  If you do not want to have to worry about
the name you can use:

library("R.utils");
l <- dim(M)[1];
for (i in (1:l)) {
  filename <- sprintf("M_%d.img", i);
  saveObject(M[i,,], file=filename);
}

and later load the object into any variable you with:

filename <- "M_32.img";
Z <- loadObject(filename);

/H

> My $.02
>
> /Henrik
>
>
>
>>
>> Can somebody help me with this? Thanks!
>>
>> Hana Lee
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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