Sisse Camilla Lundholm
Sisse Camilla Lundholm

Reputation: 261

Concatenating a nested list with differing number of elements

I am a newbie to R and have a concatenation problem that I haven't been able to solve.

I have a huge data frame of the form:

station POSIX date.str forec.time lead.time mean.ens obs

6019 2011-08-06 06:00 20110806 00 006 45 67

6019 2011-08-06 07:00 20110806 00 007 69 72

6031 2011-08-06 12:00 20110806 06 006 87 95

6031 2011-08-06 13:00 20110806 06 007 88 97

I have use "ply" to split the data frame like this

mydata.split <- dlply(mydataframe, .(datestr), dlply, .(forec.time), dlply, .(lead.time), identity, .drop = FALSE)

I do some calculation with data, which require that data are split up this way. I call this new list mynewlist af calculations. I would like to concatenate these data, but I run into problems because of differing number of list elements.

> length(mynewlist[[1]][[1]])

[1] 34

> length(mynewlist[[1]][[2]])

[1] 38

I have tried to use do.call( rbind, do.call( rbind, do.call( rbind, mynewlist) ) ) to concatenate the list into a data frame, but I get the following message:

In function (..., deparse.level = 1) : number of columns of result is not a multiple of vector length (arg 1)

Is there a way of concatenating a nested list with differing number of elements?

I am greateful for help or a point in a direction. Regard Sisse

Upvotes: 1

Views: 967

Answers (1)

Andrie
Andrie

Reputation: 179428

Just use ldply to stitch all those lists back together.

With the baseball data in plyr, use dlply as in your question to spit the data:

library(plyr)
x <- dlply(baseball, .(year), transform, mean_rbi = mean(rbi)) 

Now use ldply to combine the lists into a data.frame:

y <- ldply(x)

The results:

str(y)
'data.frame':   21699 obs. of  23 variables:
 $ id      : chr  "ansonca01" "forceda01" "mathebo01" "startjo01" ...
 $ year    : int  1871 1871 1871 1871 1871 1871 1871 1872 1872 1872 ...
 $ stint   : int  1 1 1 1 1 1 1 1 1 1 ...
 $ team    : chr  "RC1" "WS3" "FW1" "NY2" ...
 $ lg      : chr  "" "" "" "" ...
 $ g       : int  25 32 19 33 29 29 29 46 37 25 ...
 ...
 $ rbi     : int  16 29 10 34 23 21 23 50 15 16 ...
 ...
 $ gidp    : int  NA NA NA NA NA NA NA NA NA NA ...
 $ mean_rbi: num  22.3 22.3 22.3 22.3 22.3 ...

Upvotes: 1

Related Questions