[R] array to matrix or data.frame

Daniel Malter daniel at umd.edu
Mon Sep 28 01:24:25 CEST 2009


Works a charme; thanks much everybody. Daniel.


David Winsemius wrote:
> 
> 
> On Sep 27, 2009, at 6:33 PM, Daniel Malter 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.
> 
> apply(x, 2 , I)
>        [,1] [,2] [,3] [,4] [,5] [,6]
>   [1,]    1    2    3    4    5    6
>   [2,]    1    2    3    4    5    6
>   [3,]    1    2    3    4    5    6
>   [4,]    1    2    3    4    5    6
>   [5,]    1    2    3    4    5    6
>   [6,]    1    2    3    4    5    6
>   [7,]    1    2    3    4    5    6
>   [8,]    1    2    3    4    5    6
>   [9,]    1    2    3    4    5    6
> [10,]    1    2    3    4    5    6
> [11,]    1    2    3    4    5    6
> [12,]    1    2    3    4    5    6
> 
> -- 
> 
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/array-to-matrix-or-data.frame-tp25638310p25638689.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list