Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorganizing Lists of data.frames

Tags:

r

Let's say I have a list of data frames. Where each data frame has columns like this:

lists$a
company, x, y ,z
lists$b 
company, x, y, z
lists$c
company, x, y, z

Any thoughts on how I mean change it to something like:

new.list$company
a,x,y,z
b,x,y,z
c,x,y,z
new.list$company2
a,x,y,z
b,x,y,z
c,x,y,z 

I've been using:

new.list[[company]] <- ldply(lists, subset, company=company.name) 

But this only does one at a time. Is there a shorter way?

like image 438
Brandon Bertelsen Avatar asked Dec 17 '22 14:12

Brandon Bertelsen


2 Answers

Brandon,

You can use the | parameter in cast to create lists. Using the data.frame from @Wojciech:

require(reshape)
dat.m <- melt(dat_1, "company")

cast(dat.m, L1 ~ variable | company)
like image 145
Chase Avatar answered Jan 07 '23 22:01

Chase


Here's a way using the plyr package: start with @wojciech's dat_l and put the whole thing in a single data-frame using ldply:

require(plyr)
df <- ldply(dat_l)

and then turn it back into a list by splitting on the company column:

new_list <- dlply(df, .(company), subset,  select = c(.id,x,y,z) )

> new_list[1:3]
$C
   .id x         y          z
3    a 3 0.7209484  1.6247163
35   i 3 0.1630658  0.2158516
37   j 1 0.8779915 -0.9371671

$G
   .id x         y          z
2    a 2 0.1132311 -1.8067876
10   c 2 0.1825166  1.8355509
28   g 4 0.6474877 -0.8052137

$H
   .id x         y         z
1    a 1 0.9562020 -1.450522
25   g 1 0.1322886  0.584342
like image 23
Prasad Chalasani Avatar answered Jan 07 '23 22:01

Prasad Chalasani