Convert a list of data frame into a data frame
ldply in plyr package did awesome job.

I have a list with different length of data. I’d like to convert the list to a data frame with the name of the each list showing as a column. Then I can do grouping the data.
Here is an example

> test.table
$a
1 2 3 
1 1 1 
$b
1 2 3 4 
2 2 1 1 
$c
1 
1 
$d
1 3 4 
1 1 1 
$e
7 
1 
> test.table.df <- ldply(test.table, data.frame)
> test.table.df
   .id Var1 Freq
1    a    1    1
2    a    2    1
3    a    3    1
4    b    1    2
5    b    2    2
6    b    3    1
7    b    4    1
8    c    1    1
9    d    1    1
10   d    3    1
11   d    4    1
12   e    7    1

Then I can do summary or grouping the data

> tapply(test.table.df$Freq, test.table.df$Var1, sum)
1 2 3 4 7 
5 3 3 2 1 

or

> ddply(test.table.df, 'Var1', function(x) sum(x$Freq))
  Var1 V1
1    1  5
2    2  3
3    3  3
4    4  2
5    7  1

Final touch. As the grouping variable, Var1 in this example is factor. So if you want to use the level names or labels instead of levels, then you need to convert the type.

> as.numeric(levels(test.count.df$Var1))[test.count.df$Var1]
[1] 1 2 3 4 7
> test.count.df$dist <- with(test.count.df, as.numeric(levels(Var1))[Var1])                                                                                   
> test.count.df
  Var1 V1 dist
1    1  5    1
2    2  3    2
3    3  3    3
4    4  2    4
5    7  1    7

http://stackoverflow.com/questions/2851327/r-converting-a-list-of-data-frames-into-one-data-frame
http://tolstoy.newcastle.edu.au/R/help/03a/6325.html

Convert a list of data frame into a…
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *