[R] dataframe of dataframes?

Henrik Bengtsson hb at stat.berkeley.edu
Tue Sep 14 08:57:38 CEST 2010


You can create an empty matrix (or even array) of list elements and
then assign your data frames to whichever element you want.  Example:

# Allocate empty matrix...
> x <- matrix(list(), nrow=2, ncol=3);
# ...alternatively
> x <- array(list(), dim=c(2,3));
> print(x);
     [,1] [,2] [,3]
[1,] NULL NULL NULL
[2,] NULL NULL NULL

To assign a data frame to one of the elements, make sure to use double
bracket notation, e.g.

> x[[1,1]] <- data.frame(a=1, b=2:4);
> x[[1,2]] <- data.frame(c=2:3);
> x[[2,3]] <- data.frame(x=1, y=2:4);
> print(x);
     [,1]   [,2]   [,3]
[1,] List,2 List,1 NULL
[2,] NULL   NULL   List,2

Same is needed to extract an element, e.g.

> str(x[[2,3]]);
'data.frame':   3 obs. of  2 variables:
 $ x: num  1 1 1
 $ y: int  2 3 4

Compare with:

> str(x[2,3]);
List of 1
 $ :'data.frame':       3 obs. of  2 variables:
  ..$ x: num [1:3] 1 1 1
  ..$ y: int [1:3] 2 3 4

> str(x[1,]);
List of 3
 $ :'data.frame':       3 obs. of  2 variables:
  ..$ a: num [1:3] 1 1 1
  ..$ b: int [1:3] 2 3 4
 $ :'data.frame':       2 obs. of  1 variable:
  ..$ c: int [1:2] 2 3
 $ : NULL

My $.02

/Henrik

On Mon, Sep 13, 2010 at 11:18 PM, Jeff Newmiller
<jdnewmil at dcn.davis.ca.us> wrote:
> rajeshj at cse.iitm.ac.in wrote:
>>
>> Hi,
>>
>> I create several dataframes in a nested loop and would like to maintain
>> them in a matrix form with each dataframe represented by the row and the
>> column. How can I do this?
>>
>
> You can't, at least as you describe it.
>
> However, you can add a column for "row ID" and a column for "column ID" to
> each of your result data frames and "rbind" them together.
>
> It is also possible to create lists of lists... but I believe the single
> augmented dataframe will be way more useful in the long run.
>
> ______________________________________________
> 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