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

Henrik Bengtsson hb at biostat.ucsf.edu
Mon Nov 22 06:50:32 CET 2010


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]."

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);
}

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