[R] How to "flatten" a multidimensional array into a dataframe?

Marc Schwartz marc_schwartz at me.com
Thu Apr 19 22:57:21 CEST 2012


On Apr 19, 2012, at 3:46 PM, Emmanuel Levy wrote:

> Hi,
> 
> I have a three dimensional array, e.g.,
> 
> my.array = array(0, dim=c(2,3,4), dimnames=list( d1=c("A1","A2"),
> d2=c("B1","B2","B3"), d3=c("C1","C2","C3","C4")) )
> 
> what I would like to get is then a dataframe:
> 
> d1 d2 d3  value
> A1 B1 C1 0
> A2 B1 C1 0
> .
> .
> .
> A2 B3 C4 0
> 
> I'm sure there is one function to do this transformation, I just don't
> know which one.
> 
> Thanks for your help,
> 
> Emmanuel


See ?as.data.frame.table

> as.data.frame.table(my.array, responseName = "value")
   d1 d2 d3 value
1  A1 B1 C1     0
2  A2 B1 C1     0
3  A1 B2 C1     0
4  A2 B2 C1     0
5  A1 B3 C1     0
6  A2 B3 C1     0
7  A1 B1 C2     0
8  A2 B1 C2     0
9  A1 B2 C2     0
10 A2 B2 C2     0
11 A1 B3 C2     0
12 A2 B3 C2     0
13 A1 B1 C3     0
14 A2 B1 C3     0
15 A1 B2 C3     0
16 A2 B2 C3     0
17 A1 B3 C3     0
18 A2 B3 C3     0
19 A1 B1 C4     0
20 A2 B1 C4     0
21 A1 B2 C4     0
22 A2 B2 C4     0
23 A1 B3 C4     0
24 A2 B3 C4     0


Regards,

Marc Schwartz



More information about the R-help mailing list