[R] array to matrix or data.frame

Gabor Grothendieck
Sun, 27 Sep 2009 22:58:47 -0000

Try this:

matrix(aperm(x, c(1,3,2)), nc = 6)


On Sun, Sep 27, 2009 at 6:33 PM, Daniel Malter <daniel at umd.edu>
wrote:
>
> Hi, I have an array of dimension 6:6:160000. I want to stack the 160000
> slices of the array into a matrix or a data frame of dimension
> 6:(6*160000=960000) in order to write it to a csv file. It seems I cannot
> get the matrix or data.frame functions to put the values from the array in
> the same order as they appear in the array easily, but I am almost sure
> there is an easy way to do this.
>
> #Here is code for a small 6:6:2 array.
>
> x=rep(rep(1:6,each=6),2)
> dim(x)=c(6,6,2)
>
> x
>
> #Matrix approach 1:
>
> matrix(x,nrow=12,ncol=6,byrow=F)
>
> #Matrix approach 2:
>
> matrix(x,nrow=12,ncol=6,byrow=T)
>
> #Data frame approach (cbinds rather than rbinds):
>
> data.frame(x)
>
> None of the above works as I would like to. The "correct"
approach should
> stack the same values all in the same column of the matrix or data frame. I
> also could not get "stack" to work correctly and would appreciate
your help.
>
> Daniel
>
>
>
> --
> View this message in context:
http://www.nabble.com/array-to-matrix-or-data.frame-tp25638310p25638310.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.
>